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

时间:2016-06-28 16:05:29

标签: javascript reactjs method-call

我想在同一个类中调用该方法。例如,当我单击一个按钮时,它将触发方法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

错误讯息:

{{1}}

2 个答案:

答案 0 :(得分: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() {
        ...
    }

    ...
    ..
    .
}

答案 1 :(得分:2)

你绑定handleLoginBtnClicked的位置是什么?您可能正在丢失函数上下文并失去特殊变量this的含义。 React将处​​理并触发onClick事件,从不同的上下文调用该函数,这就是它丢失的原因。

您应该使用以下语法创建一个新的绑定函数,以添加为onClick事件的事件侦听器。这将确保handleLoginBtnClicked的上下文不会丢失。

<element onClick={this.handleLoginBtnClicked.bind(this)}>
相关问题