React 事件处理为什么推荐调用 bind(this)

#1

<div className="save" onClick={this.handleClick.bind(this)}>click</div>

我知道 js 中 this 指针的问题,也知道 ES6 箭头函数的 this。

但是,我很不清楚,为什么这里推荐要绑定 this:bind(this),是因为担心 handleClick 函数会在其他地方被调用么?如果仅仅是在当前组件中,那么,this 一定是不会改变的吧????

为什么这里要用 bind(this),好困惑啊。。。。

还是说用 bind(this, arg),为了传参,绑定 this 是顺带的事?

#2

We generally recommend binding in the constructor or using the property initializer syntax, to avoid this sort of performance problem.

官方推荐的是在constructor中bind,或者箭头函数class属性初始化语法。

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>
    );
  }
}


class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}
#3

和 React 关系不大,在 <div> 上调用 this.xxxx,你说这个 this 是啥

#4

嗯,那就回到this指针的问题了,@dongweicai,如果这里不做bind,那么如果在handleClick里面调用了this.xxx,那么答案就是如下:

If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

还是见文档

#5

bind(this)是把事件绑定到react组件上面。箭头函数默认是执行了bind(this)的

#6

谢谢,了解了:slight_smile: