距开课0天0时0分-10074501秒
大家讲道理2017-06-28 09:26:21 0 2 353
[JavaScript讨论组]举报回复话题 ↕
<button onClick={this.handleEvent}> //这里的this是toggle组件 为什么还需要在组件里绑定这个函数的this {this.state.isToggleOn === true ? 'on' : 'off'} </button>
想不明白这里的this绑定
2
0
分享
三叔 2017-06-28 09:28:212楼
因为在class中声明函数,并不会自动绑定this对象
class
this
所以,你在onClick={this.handleEvent}的时候,分解成两步你就懂了:
onClick={this.handleEvent}
let handleEvent = this.handleEvent; ...onClick={handleEvent}...
所以,onClick调用的时候,handleEvent中的this会是undefined(根据文档)
onClick
handleEvent
undefined
所以,你需要bind一下, 那么里面的this就是当前组件啦。
bind
还有一种方便的写法,就是用箭头函数声明:
handleEvent = (e)=>{ } render(){ ...onClick={this.handleEvent}... }
赞 +0添加回复
给我你的怀抱 2017-06-28 09:28:211楼
因为handleEvent中this.setState...的this并没有绑定this
可以采用箭头函数的语法糖来绑定this
handleEvent = () => { this.setState... }
三叔 2017-06-28 09:28:212楼
因为在
class
中声明函数,并不会自动绑定this
对象所以,你在
onClick={this.handleEvent}
的时候,分解成两步你就懂了:所以,
onClick
调用的时候,handleEvent
中的this
会是undefined
(根据文档)所以,你需要
bind
一下, 那么里面的this
就是当前组件啦。还有一种方便的写法,就是用箭头函数声明:
赞 +0添加回复
给我你的怀抱 2017-06-28 09:28:211楼
因为handleEvent中this.setState...
的this并没有绑定this
可以采用箭头函数的语法糖来绑定this
赞 +0添加回复