<button onClick={this.handleEvent}> //这里的this是toggle组件 为什么还需要在组件里绑定这个函数的this
{this.state.isToggleOn === true ? 'on' : 'off'}
</button>
想不明白这里的this绑定
<button onClick={this.handleEvent}> //这里的this是toggle组件 为什么还需要在组件里绑定这个函数的this
{this.state.isToggleOn === true ? 'on' : 'off'}
</button>
想不明白这里的this绑定
还是对this的理解问题,this的值一直会延迟到运行时。用下面的代码演示你的问题:
let toggle = {
name: 'Toggle',
handleEvent: function() {
console.log(this.name);
}
}
let button = {};
button.click = toggle.handleEvent;
button.click2 = toggle.handleEvent.bind(toggle);
toggle.handleEvent(); //Toggle //这里的this是toggle
button.click(); //undefined //这里的this是button
button.click2(); //Toggle //这里的this永远是toggle
因为handleEvent中this.setState...
的this并没有绑定this
可以采用箭头函数的语法糖来绑定this
handleEvent = () => {
this.setState...
}
super()在子类constructor构造方法中是为了获取this上下文环境,所以如果在constructor中使用到this,必须在使用this之前调用super(),反之不在constructor中使用this则不必调用super(),这样子类才继承了父类的方法,在虚拟子类DOM中调用 this+ 父类方法。
es5 自动绑定 {this.abc} abc:function(){}
es6
1.使用bind绑定 {this.abc.bind(this)} abc(){}
2.箭头函数绑定 {this.abc} abc = () => {}
3.调用时使用箭头 {()=>this.abc} abc(){}
。。。。
官方文档
You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
因为在
class
中声明函数,并不会自动绑定this
对象所以,你在
onClick={this.handleEvent}
的时候,分解成两步你就懂了:所以,
onClick
调用的时候,handleEvent
中的this
会是undefined
(根据文档)所以,你需要
bind
一下, 那么里面的this
就是当前组件啦。还有一种方便的写法,就是用箭头函数声明: