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

Cas*_*per 5 javascript method-call 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}/>
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

Uncaught TypeError: this.checkInputValidation is not a function
Run Code Online (Sandbox Code Playgroud)

Elo*_*pos 6

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

    ...
    ..
    .
}
Run Code Online (Sandbox Code Playgroud)