Why is that? 1. If you pass a function name to a variable and then call it as a function name (), the reference to this will be lost if you use this inside the method.

Sample code:

First we create the test object and call the method directly:

const test = {

name:'jack',

getName:function(){

    console.log(this.name)

}
Copy the code

}

test.getName()

const test = {

name:'jack',

getName:function(){        console.log(this.name)

}
Copy the code

}

test.getName()

Executing the above code using Node test.js will print jack normally.

After that, we adjust the code:

const test = {

name:'jack',

getJack:function(){

    console.log(this.name)

}
Copy the code

}

const func = test.getJack;

func();

Instead of calling the object’s method directly, we declare the method to an intermediate variable, and then use the intermediate variable () to call the method. In this case, we lose the reference and print undefined. If we use the Node environment to execute the js file, we print node information. If embedded in HTML, this points to the window object.

In JSX, bind is not a string, but a function (e.g. OnClick ={this.handleclick}). OnClick is an intermediate variable, so the “this” pointer in the handler is lost. The solution to this problem is to bind(this) to the calling function so that this points to the currently instantiated object regardless of how the event handler is passed.

Of course, if you don’t want to use bind(this), you can use the arrow function to return the function contents to a variable when declaring the function, and use this directly when calling it. The variable name will do. Example code is as follows:

import React from ‘react’;

export default class Life extends React.Component{

constructor(props){ super(props); this.state = { count:4 }; } render(){ var style = { padding:'10px', color:'red', FontSize :'30px'} return (<div style={style}>{/* notice that js syntax uses parenthesize {},style uses two parenthesize */} <p>React life cycle </p> <button <button onClick={this.handleclick. bind(this)}> </button> <p>{this.state.count}</p> </div>)} handleAdd = ()=> {console.log(this) this.setState({count:5})}  handleClick(){ this.setState({ count:6 }) }Copy the code

}

REACT BIND(THIS) : BIND(THIS)

handleClick(){

this.setState({

word2:’word2 changed’

})

}

Click on the

2. Use the ES6 arrow function

handleClick=()=>{

this.setState({

word2:’word2 changed’

})

}

Click on the

Constructor bind(this)

constructor(props){

super(props);

this.state=({

word2:’word2′

})

this.handleClick = this.handleClick.bind(this);

}