<button onClick={this.handleEvent}> //这里的this是toggle组件 为什么还需要在组件里绑定这个函数的this {this.state.isToggleOn === true ? 'on' : 'off'} </button>
I don’t understand the this binding here
光阴似箭催人老,日月如移越少年。
Because when a function is declared in class, it will not be automatically bound to thisobject
class
this
So, when you onClick={this.handleEvent}, break it down into two steps and you will understand:
onClick={this.handleEvent}
let handleEvent = this.handleEvent; ...onClick={handleEvent}...
So, when onClick is called, this in handleEvent will be undefined (according to the documentation)
onClick
handleEvent
undefined
So, you need to bind, then this inside is the current component.
bind
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... }
Because when a function is declared in
class
, it will not be automatically bound tothis
objectSo, when you
onClick={this.handleEvent}
, break it down into two steps and you will understand:So, when
onClick
is called,this
inhandleEvent
will beundefined
(according to the documentation)So, you need to
bind
, thenthis
inside is the current component.There is also a convenient way to write it, which is to declare it with an arrow function:
Because this.setState...
in handleEvent is not bound to this
You can use the syntactic sugar of arrow functions to bind this