gpt4 book ai didi

javascript - React-JavaScript 代码中一行的用途

转载 作者:行者123 更新时间:2023-11-30 11:13:11 26 4
gpt4 key购买 nike

这是一个非常简单的问题,但我正在学习过程中,在阅读之后我无法在下面的代码中找到一个很好的解释:该行的目的是什么:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com