How to call multiple functions on the same onClick event ReactJS

后端 未结 3 934
予麋鹿
予麋鹿 2020-12-14 23:57

I have this function and when I click on the

  • tag, I want to call two functions, onClick={handleProjectSelection(project)} a handler func
  • 相关标签:
    3条回答
    • 2020-12-15 00:28

      You can Wrap your two+ function calls in another function/method. For example

      var Test = React.createClass({
         onClick: function(event){
            func1();
            func2();
         },
         render: function(){
            return (
               <a href="#" onClick={this.onClick}>Test Link</a>
            );
         }
      });
      
      0 讨论(0)
    • 2020-12-15 00:37

      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();
      }}
      
      0 讨论(0)
    • 2020-12-15 00:38

      You can do it in two ways:
      1.

      onClick={()=>{
          callFunctionOne();
          callFunctionTwo();
      }}
      

      2.

      callTwoFunctions(){
          callFunctionOne();
          callFunctionTwo();
      }
      
      onClick={this.callTwoFunctions}
      
      0 讨论(0)
    提交回复
    热议问题