这是一个非常简单的问题,但我正在学习过程中,在阅读之后我无法在下面的代码中找到一个很好的解释: 该行的目的是什么:
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>
)
}
最佳答案
this.buttonClicked = this.buttonClicked.bind(this);
这一行基本上允许您在buttonClicked()
函数中使用this
。
您没有注意到差异,因为您实际上并未在该函数中使用 this
。
尝试在 buttonClicked()
中使用 this
并注释掉绑定(bind)行,您应该会得到一个错误。
为避免需要手动绑定(bind),您可以使用箭头函数,例如:
buttonClicked = () => {
// do something with `this`
}
关于javascript - React-JavaScript 代码中一行的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52780284/