![](/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.