![](/img/trans.png)
[英]How to call a method inside getDerivedStateFromProps in ReactJS?
[英]How to call method inside the same class in ReactJS?
我想在同一個類中調用該方法。 例如,當我單擊一個按鈕時,它將觸發方法handleLoginBtnClicked()
。 我希望它會在同一個類中調用checkInputValidation()
方法。 這樣做的正確方法是什么?
export default class LoginCard extends React.Component {
//If I click a button, this method will be called.
handleLoginBtnClicked() {
this.checkInputValidation();
}
checkInputValidation() {
alert("clicked");
}
...
...
...
render() {
...
<LoginBtn onClick={this.handleLoginBtnClicked}/>
...
}
}
錯誤信息:
Uncaught TypeError: this.checkInputValidation is not a function
您需要將這些函數綁定到組件的上下文。 在constructor
您需要執行以下操作:
export default class LoginCard extends React.Component {
constructor(props) {
super(props);
this.handleLoginBtnClicked = this.handleLoginBtnClicked.bind(this);
this.checkInputValidation = this.checkInputValidation.bind(this);
}
//This is the method handleLoginBtnClicked
handleLoginBtnClicked() {
...
}
//This is the method checkInputValidation
checkInputValidation() {
...
}
...
..
.
}
你在哪里綁定handleLoginBtnClicked
? 你可能會失去功能的情況下,失去的特殊變量的含義this
。 React將處理並觸發onClick
事件,從不同的上下文調用該函數,這就是它丟失的原因。
您應該使用以下語法創建一個新的綁定函數,以添加為onClick事件的事件偵聽器。 這將確保handleLoginBtnClicked
的上下文不會丟失。
<element onClick={this.handleLoginBtnClicked.bind(this)}>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.