作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我想调用同一个类中的方法。例如,当我点击一个按钮时,它会触发方法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/
我是一名优秀的程序员,十分优秀!