Methods in class do not bind this by default, so if this is used in an event handler, you must bind this manually. Four methods are described:
The first is bound in the constructor
- Advantages: Good performance, only one method instance is generated,
- Disadvantages: Can’t carry parameters, need to add extra code
class LoggingButton extends React.Component { constructor(props){ super(props) this.state={} this.handleClick=this.handleClick.bind(this) } handleClick (){ ... } render() { return ( <button onClick={this.handleClick}> Click me </button> ); }}Copy the code
The second is call-time binding
- Advantages: Can carry parameters, no extra code,
- Disadvantages: Each invocation generates a new method instance, poor performance
class LoggingButton extends React.Component { constructor(props){ super(props) this.state={} } handleClick (val){ ... } render() { return ( <button onClick={this.handleClick.bind(this,'a')}> Click me </button> ); }}Copy the code
The third call is made with an arrow function (the arrow function’s this points to the object in the scope in which the function was defined).
- The advantages and disadvantages are the same as the second way
class LoggingButton extends React.Component { constructor(props){ super(props) this.state={} } handleClick (val,e){ ... } render() { return ( <button onClick={(e)=>this.handleClick('a',e)}> Click me </button> ); }}Copy the code
The fourth method is declared with arrow functions
- Advantages: Good performance, no extra code, only one instance generated
- Disadvantages: Can’t carry extra parameters
class LoggingButton extends React.Component { constructor(props){ super(props) this.state={} } handleClick= (val) => { . } render() { return ( <button onClick={this.handleClick}> Click me </button> ); }}Copy the code
Explanation 1
To carry parameters other than event, only the second and third methods can be used. If it is the props of a child component, the child component will be re-rendered every time the parent component is updated, resulting in the Maximum update depth exceeded
Instruction 2
If this is not bound and is used as onClick={this.test()}, the event will only be triggered during the initial rendering, not the click. The complete code is as follows:
class LoggingButton extends React.Component { handleClick (){ ... } render() { return ( <button onClick={this.handleClick()}> Click me </button> ); }}Copy the code