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

标签 javascript reactjs method-call

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

相关文章:

javascript - react / typescript 错误 : Operator '<' cannot be applied to types 'boolean' and 'RegExp'

java - Java 中方法调用和参数之间的求值顺序

javascript - "Origin null is not allowed by Access-Control-Allow-Origin."使用 jQuery 调用 Web 服务时出错

javascript - 如何在 native react 中使用 justify content 属性?

javascript - HTML: JQuery 如何使用JQuery获取data-dk-dropdown-value

javascript - 使用 react-router-dom v6.0.2 检测用户离开页面

java - 如果类名作为字符串传递,如何动态调用类的方法

java - "Iterating"通过方法

javascript - 重叠jquery鼠标悬停事件

javascript - Prototype 的 Ajax 功能的语法糖