[react] this in react

Time:2021-6-14
class App extends React.Component{
  constructor(props) {
    super(props);
    //To make this point to the current class
    // this.handleClick = this.handleClick.bind(this);
  }
  
  //Test function
  handler() {
    Console.log (` handler is called, this points to: ', this));
  }
 
  render(){
    return(
        <div>
          <h1>hello World</h1>
            < label htmlfor ='btn '> click this in the print function handler to point to < / label >
            < input id = {BTN "type = button" value ='click 'onclick = {this. Handler} / >
       </div>        
   )
 }
}

Output “handler called, this points to: undefined”, because this only specifies the callback function for the click event. This function is called only when the event is triggered. At this time, it is not clear who called this function in the click synthesis function (so this is undefined with uncertainty, and an error will be reported if this.setstate is used)

Automatic binding and manual binding

  • React.createclass can automatically bind this of the method to the component instance. Other ES6 class syntax will not bind this environment, so it needs to be bound manually
  • So we usually bind this point of the method in the constructor

summary

  • In the react component life cycle function, this points to the component instance
  • This in the custom component function will vary according to the caller
  • In order to get the component instance in the component function, you need to manually bind this to the component instance

    • In the constructor functionthis.handleClick = this.handleClick.bind(this);
    • Bind this when binding events<div onClick = {this.handler.bind(this)} >
    • Defining methods using arrow functions<div onClick = {() => this.handler()} >Or write the function as an arrow function
    • Using ES7::