Closed sunmingtao closed 4 years ago
Print this
to console. It shows this
refers to the App
object
changeName(){
console.dir(this);
this.setState({
name: 'Anna'
});
}
Now remove .bind(this)
, this
evaluates to undefined
(why? I thought it should be the button)
So bind(this)
ensures the this
in changeName() method refers the App object.
Alternatively, we can change the changeName() to an arrow function
changeName = () => {
this.setState({
name: 'Anna'
});
}
.bind(this)
then becomes unnecessary.
onClick={this.changeName}
is good enough.
When a function is defined as arrow function, this
always refers to the object in which the function is defined, regardless which object calls the function.