簡體   English   中英

代碼中一行的React-JavaScript目的

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM