<button onClick={this.handleEvent}> //这里的this是toggle组件 为什么还需要在组件里绑定这个函数的this
{this.state.isToggleOn === true ? 'on' : 'off'}
</button>
I don’t understand the this binding here
三叔2017-06-28 09:28:21
Because when a function is declared in class
, it will not be automatically bound to this
object
So, when you onClick={this.handleEvent}
, break it down into two steps and you will understand:
let handleEvent = this.handleEvent;
...onClick={handleEvent}...
So, when onClick
is called, this
in handleEvent
will be undefined
(according to the documentation)
So, you need to bind
, then this
inside is the current component.
There is also a convenient way to write it, which is to declare it with an arrow function:
handleEvent = (e)=>{
}
render(){
...onClick={this.handleEvent}...
}
给我你的怀抱2017-06-28 09:28:21
Because this.setState...
in handleEvent is not bound to this
You can use the syntactic sugar of arrow functions to bind this
handleEvent = () => {
this.setState...
}