![](/img/trans.png)
[英]React-javascript : My react input isn't working. It becomes immutable once i set the Value
[英]React-JavaScript purpose of a line in the code
這是一個非常簡單的問題,但我在學習過程中,在閱讀后我無法找到一個很好的解釋,在下面的代碼中:該行的目的是什么:
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);
這條線基本上可以讓你使用this
你中buttonClicked()
函數。
您沒有注意到差異,因為您實際上沒有在該函數中使用this
。
在buttonClicked()
嘗試使用this
,並將綁定行注釋掉,您應該收到錯誤。
為避免需要手動綁定,您可以使用箭頭功能,如:
buttonClicked = () => {
// do something with `this`
}
bind
用於綁定上下文。 在其他答案中已經給出了解釋。
您可以使用以下語法而不是注釋行
onClick={this.buttonClicked.bind(this)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.