React - 为什么在这个例子中不需要绑定?

Ada*_*dam 3 binding reactjs

试图找出React的基础知识.

查看本页的第二个例子:https://facebook.github.io/react/ 我看到tick()函数设置Timer类的状态,将前一个值递增一.

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {secondsElapsed: 0};
  }

  tick() {
    this.setState((prevState) => ({
      secondsElapsed: prevState.secondsElapsed + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
      <div>Seconds Elapsed: {this.state.secondsElapsed}</div>
    );
  }
}

ReactDOM.render(<Timer />, mountNode);
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试实现我自己的简单Counter类时,它失败了,我得到一个控制台错误,说无法读取未定义的属性setState.

class Counter extends React.Component {
    constructor(props) {
        super(props);
        this.state = {count: 0};
    }

    increment(prevState) {
        this.setState((prevState) => ({
            count: prevState.count + 1
        }));
    }

  render() {
    return (
            <div className="main">
                <button onClick={this.increment}>{this.state.count}</button>
            </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

一些谷歌搜索显示我必须将它绑定到增量函数.但是为什么在我看到的第一个例子中不需要这个?我将代码复制到CodePen,它与React 15.3.1运行良好我在该示例中找不到任何类似绑定的内容.只有在构造函数中添加了绑定代码后,才会在我的示例中开始工作.

class Counter extends React.Component {
    constructor(props) {
        super(props);
        this.state = {count: 0};

        // THIS ONE LINE FIXED THE ISSUE
        this.increment = this.increment.bind(this);
    }

    increment(prevState) {
        this.setState((prevState) => ({
      count: prevState.count + 1
    }));
    }

  render() {
    return (
            <div className="main">
                <button onClick={this.increment}>{this.state.count}</button>
            </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

mrl*_*lew 16

回答你的问题:第一个例子使用arrow functions,自动执行上下文绑定.来自文档:

箭头函数不会创建自己的此上下文,因此它具有封闭上下文的原始含义.

确实在React中有一些绑定方式:

1)你可以绑定构造函数中的所有函数,就像你说的:

constructor(props) {
    /* ... */
    this.increment = this.increment.bind(this);
}
Run Code Online (Sandbox Code Playgroud)

2)使用箭头函数调用您的回调:

<button onClick={(e) => this.increment(e)}>
Run Code Online (Sandbox Code Playgroud)

3).bind每次将其设置为回调时附加在方法引用的末尾,如下所示:

<button onClick={this.increment.bind(this)}>
Run Code Online (Sandbox Code Playgroud)

4)在您的班级中,使用箭头功能定义方法:

increment = (e) => {
  /* your class function defined as ES6 arrow function */
}

/* ... */

<button onClick={this.increment}>
Run Code Online (Sandbox Code Playgroud)

要在babel中使用此语法,您必须启用此插件或使用stage-2预设.

  • *我也意识到我将回调设置为{this.increment}而不是{this.increment()}*你不应该把括号括起来.你必须只传递引用:如果你放括号,你将调用方法,并将返回传递给括号. (2认同)
  • 如果可能,我建议阅读[this](https://github.com/getify/You-Dont-Know-JS/tree/master/this%20%26%20object%20prototypes).您也可以查看[this](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/this)参考. (2认同)