簡體   English   中英

如何在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM