Since class methods do not bind this by default, you need to manually bind this and several methods of this when calling
1. Bind this in the constructor by bind
class ReactHandle extends React.PrueComponent{ constructor(props){ this.handler=this.handler.bind(this) } bandler(){ Console. log(' bind this in constructor ')} render(){return <div onClick={this.bandler}> Bind this </div>}}Copy the code
2. Bind this with bind when called
Class ReactHandle extends react.pruecomponent {bandler(){console.log(' bind this in constructor ')} render(){return <div OnClick ={this.bandler.bind(this)}> Bind this </div>} in the constructor.Copy the code
3. Bind this via the arrow function at call time
Class ReactHandle extends react.pruecomponent {bandler(){console.log(' bind this in constructor ')} render(){return <div OnClick ={()=>this.bandler()}> Bind this </div>}} in the constructorCopy the code
4. Use new experimental methods
Class ReactHandle extends react. PrueComponent{bandler=()=>{console.log(' bind this in constructor ')} render(){return <div OnClick ={this.bandler}> Bind this </div>}} in the constructorCopy the code
To compare
** (2) and (3)** bind this at call time.
- ** Advantages: ** There is no need to add a class constructor to bind this when there is no state in the component
- ** Disadvantages: ** A new method instance is generated each time a call is made, so there is a performance impact, and when this function is passed as a property value to lower-level components, those components may perform additional re-rendering because each time a new method instance is passed as a new property.
**(1)** Bind this to the class constructor and do not need to bind it when called
- ** Advantages: ** generates only one method instance, and does not bind the method if it is used multiple times after binding.
- ** Disadvantages: ** You need to add a class constructor to bind this even if you don’t need state.
**(4) : Initializes a method as an arrow function using attribute initialization syntax, so this is bound when the function is created. Advantages: This is bound when the method is created, not in the class constructor, and does not need to be bound when called. Combine the advantages of (1), (2) and (3)** Disadvantages: ** requires Babel translation
conclusion
Mode 1 is the recommended binding mode and has the best performance. (2) and (3) have a performance impact and can cause rerendering problems when methods are passed as attributes to child components. (4) It is an experimental syntax at present, but it is the best binding method, which requires bable translation