gpt4 book ai didi

javascript - 如何在 ReactJS 的同一个类中调用方法?

转载 作者:数据小太阳 更新时间:2023-10-29 06:00:35 25 4
gpt4 key购买 nike

我想调用同一个类中的方法。例如,当我点击一个按钮时,它会触发方法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

最佳答案

您需要将这些函数绑定(bind)到组件的上下文中。在 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() {
...
}

...
..
.
}

关于javascript - 如何在 ReactJS 的同一个类中调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38081154/

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