首页 > 解决方案 > 代码中一行的 React-JavaScript 用途

问题描述

这是一个非常简单的问题,但我正在学习过程中,在阅读之后我找不到一个很好的解释,在下面的代码中:What is the purpose of the line:

this.buttonClicked = this.buttonClicked.bind(this);

如果我评论它,该程序仍在运行。很可能有一些副作用,但我还不知道......

class test extends React.Component {
constructor(props){
    super(props)
    //this.buttonClicked = this.buttonClicked.bind(this);
}

buttonClicked() {
    alert("thank you!")
}

render() {
    return (
        <div>
          <h2>{this.props.text}</h2>
          <button onClick={this.buttonClicked}>click me!</button>
        </div>
    )
}

}

标签: javascriptreactjs

解决方案


this.buttonClicked = this.buttonClicked.bind(this);

这条线基本上允许你this在你的buttonClicked()函数中使用。

您不会注意到差异,因为您实际上并未this在该功能中使用。

thisbuttonClicked()注释掉绑定行的情况下尝试使用inside,您应该会收到错误消息。

为避免需要手动绑定,您可以使用箭头函数,例如:

buttonClicked = () => {
  // do something with `this`
}

推荐阅读