React 回调函数中的this

当你使用 ES6 class 语法来定义一个组件的时候,事件处理器会成为类的一个方法。例如,下面的 Toggle 组件渲染一个让用户切换开关状态的按钮:

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

官方解释:JSX 回调函数handleClick()中的 this,类的方法默认是不会绑定 this 的。如果你忘记绑定 this.handleClick 并把它传入 onClick, 当你调用这个函数的时候 this 的值会是 undefined

我的理解:

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

回调函数,即事件处理函数中的this是单独在该函数内存在的,使用类定义组件的方法,不会主动将回调函数中的this绑定到该组件对象上,倘若要使用该回调函数结合组件内其他量做一些处理,那么需要将组件内该方法显示得绑定到该组件对象this上。

上文绑定方法:

    // This binding is necessary to make `this` work in the callback
    //为了使回调函数中this工作,这里的绑定是必须的。
    this.handleClick = this.handleClick.bind(this);

 该绑定的代码中,this代表的是回调函数对象,这句代码可以理解为:将该组件中的handleClick回调函数绑定到该组件上,实质上是将回调函数中的this指向该组件对象,然后将改变了执行上下文的回调函数,再重新替换掉原来的handleClick回调函数,那么此时的回调函数中的this指向的是类定义的组件。

 

这并不是 React 的特殊行为;它是函数如何在 JavaScript 中运行的一部分。通常情况下,如果你没有在方法后面添加 () ,例如 onClick={this.handleClick},你应该为这个方法绑定 this

官方文档详细资料:http://react.yubolun.com/docs/handling-events.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值