[英]How to call method inside the same class in ReactJS?
I want to call the method inside the same class. 我想在同一个类中调用该方法。 For example, when I click a button, it will trigger the method handleLoginBtnClicked()
. 例如,当我单击一个按钮时,它将触发方法handleLoginBtnClicked()
。 I expect it will call the method checkInputValidation()
in the same class. 我希望它会在同一个类中调用checkInputValidation()
方法。 What is the proper way to do this? 这样做的正确方法是什么?
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}/>
...
}
}
Error Message: 错误信息:
Uncaught TypeError: this.checkInputValidation is not a function
You will need to bind those functions to the context of the component. 您需要将这些函数绑定到组件的上下文。 Inside constructor
you will need to do this: 在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() {
...
}
...
..
.
}
Where are you binding the handleLoginBtnClicked
? 你在哪里绑定handleLoginBtnClicked
? You may be losing the functions context and losing the meaning of the special variable this
. 你可能会失去功能的情况下,失去的特殊变量的含义this
。 React will handle and trigger the onClick
event, calling the function from a different context which is why it has been lost. React将处理并触发onClick
事件,从不同的上下文调用该函数,这就是它丢失的原因。
You should use the following syntax to create a new bound function to add as the event listener for the onClick event. 您应该使用以下语法创建一个新的绑定函数,以添加为onClick事件的事件侦听器。 This will ensure that handleLoginBtnClicked
's context is not lost. 这将确保handleLoginBtnClicked
的上下文不会丢失。
<element onClick={this.handleLoginBtnClicked.bind(this)}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.