React中组件绑定this

图片描述

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

想不明白这里的this绑定

阅读 5.5k
7 个回答

因为在class中声明函数,并不会自动绑定this对象

所以,你在onClick={this.handleEvent}的时候,分解成两步你就懂了:

let handleEvent = this.handleEvent;
...onClick={handleEvent}...

所以,onClick调用的时候,handleEvent中的this会是undefined根据文档

所以,你需要bind一下, 那么里面的this就是当前组件啦。

还有一种方便的写法,就是用箭头函数声明:

handleEvent = (e)=>{

}

render(){
  ...onClick={this.handleEvent}...
}
const Toggle = React.createClass({
    //...觉得不好理解换成这种方式就不用bind  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.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题