javascript - Component binding this in React
大家讲道理
大家讲道理 2017-06-28 09:26:21
0
2
775

<button onClick={this.handleEvent}>    //这里的this是toggle组件 为什么还需要在组件里绑定这个函数的this 
  {this.state.isToggleOn === true ? 'on' : 'off'}
</button>

I don’t understand the this binding here

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
三叔

Because when a function is declared in class, it will not be automatically bound to thisobject

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}...
}
给我你的怀抱

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...
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template