Reputation: 430
As you know we can use ES6 in React since 0.13. And I found below syntax to define an event handler:
class MyComponent extends React.Component {
handleClickEvent = evt => {
this.setState({value: evt.target.value});
}
render() {
return <div onClick={this.handleClickEvent} />;
}
}
By this syntax we don't need to use this.handleClickEvent.bind(this)
. I've searched a lot but still didn't find out why this
in the method handleClickEvent
is in the correct scope. Anyone could help? Thanks in advance!
Upvotes: 2
Views: 119
Reputation: 77522
Because you are using =>
arrow function.,
Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.
With not arrow functions
you should you should set this
to function by yourself
class MyComponent extends React.Component {
constructor() {
super();
this.handleClickEvent = this.handleClickEvent.bind(this);
// ^^^^^^^^^^^
}
handleClickEvent() {
this.setState({value: evt.target.value});
}
render() {
return <div onClick={this.handleClickEvent} />;
}
}
Upvotes: 5