why react component bind this in constructor

In many react component's constructor, developers always bind its methods with this, like:

export default class MyComponent extends Component {
constructor() {
this.say = this.say.bind(this)
}
...
}

This sentence seems to be stupid. Is this regulated by react?

No!

In fact, react component class follow ES6 class std. The reason to put this sentence is because when you use this.say in your render, you alway use it as onClick callback function, this is why this is not point to instance of this component. Let's look into this code:

<a href="" onclick="alert(this.href)">click</a>

You know what this point to here, so when you use a component method as a event callback function, this in the function does not referer to the instance of component. So another way to solve this problem is to bind this when you use the method, like:

export default class MyComponent extends Component {
constructor() {
// do not use bind sentence
}
render() {
return <a onClick={this.say.bind(this)}>click</a>
}
}

Now you can use this in say as want you want.

2017-09-30 01:34:09