Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - How to call multiple functions on the same onClick event ReactJS

I have this function and when I click on the <li> tag, I want to call two functions, onClick={handleProjectSelection(project)} a handler function that comes from props from the parent component, and also this function onClick={() => this.setState({ showingProjectSelector: false })}

  renderDropdown () {
    const { displayDropdown, projects, handleProjectSelection } = this.props
    if (this.state.showingProjectSelector && displayDropdown) {
      const projectsList = projects.map((project) => (
        <li className='u-cursor--pointer u-font-size--12px'
          key={project.get('id')}
          onClick={handleProjectSelection(project)} >
          <i className='fa fa-square u-font-size--10px' style={{color: project.get('color')}}></i>
          {project.get('name')}
        </li>
      ))

How can I call this two functions? This is the handler function from the parent component

  handleProjectSelection = (project) => () => {
    this.setState({
      projectToAdd: project.get('id'),
      projectToAddColor: project.get('color'),
      projectToAddName: project.get('name') === 'default' ? 'No' : project.get('name').substring(0, 2)
    })
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Write it like this:

onClick={() => {
   handleProjectSelection(project);
   anotherfunctionCall();
}}

Or create a single function, use that as a click handler. Inside that function call other two functions, Like this:

onClick={this.handleClick}

handleClick(){
   function1();
   function2();
}

See there are two ways of using arrow function:

1- Concise Body: () => /*single expression*/

2- Block Body: () => {}

In block body inside {} (body of the function), we can perform any number of task.

Like this:

onClick={() => {
   fun1();
   fun2();
   fun3();
   fun4();
   ....
   funN();
}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...