Four ways to react in solving this problem point

I believe we learn and react in the process, little attention will appear this point to the wrong problem, which is a relatively good solution, but still makes a headache, then the following to say about the four written to solve this problem.

I. Definition behind interline events using bind bind this

run(){
Alert ( "The first method!" )
}

<button onClick={this.run.bind(this)}>第一种</button>

 

This method uses a modification to bind to this point, to note that the first parameter within the parentheses bind this modification, the latter may be provided other parameters by value.

II. In the constructor declared inside this point

constructor(props) {
super(props);
the this .STATE = {
 // definition data 
}
 the this .run = the this .run.bind ( the this );
}

run(){
Alert ( "The second way!" )
}

<Button the onClick = { the this .run}> second </ button>

 



The second method and the first method the same principle, just write different locations.

III. When you declare an event equal to the event an arrow function

run=()=> {
Alert ( "third method!" )
}

<Button the onClick = { the this .run}> third </ button>

 


A third method is to re-run method defined function equal to an arrow by arrow pointer this function does not inherit their outer scope of this characteristic, this refers to solve the problem

IV. Use the arrow between the lines defined event function

run(){
Alert ( "The fourth method!" )
}

<button onClick={()=>this.run()>第四种</button>

 


The fourth principle of the method and the third method is the same, just different wording, it depends on personal preference.

Overall, the changes in this issue point to point can be modified through the use of this bind, you can also use the arrow functions to solve. If there are better and more clever way, I hope you can tell me comments, encourage each other!
----------------
Disclaimer: This article is CSDN blogger "dust raw Kakitsubata Dian" in the original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/weixin_43851769/article/details/88096457

Guess you like

Origin www.cnblogs.com/ygunoil/p/12105190.html