简体   繁体   中英

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() . I expect it will call the method checkInputValidation() in the same class. 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:

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 ? You may be losing the functions context and losing the meaning of the special variable this . React will handle and trigger the onClick event, calling the function from a different context which is why it has been lost.

You should use the following syntax to create a new bound function to add as the event listener for the onClick event. This will ensure that handleLoginBtnClicked 's context is not lost.

<element onClick={this.handleLoginBtnClicked.bind(this)}>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM