如何在反应类Es6中的另一个方法中调用方法

Seu*_*ege 7 javascript ecmascript-6 reactjs

所以我基本上想要做的就是简单

class Something extends React.Component {

validateEmail () {
//code that validates email,innerHTML a div.status element if error occurs
this.removeStatus();//then remove status onkeydown of input element
 }

removeStatus () {
//code that removes the status onkeydown of input element

 }
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,它不起作用.在我的JavaScript控制台(铬)我得到这个

login.js:132Uncaught TypeError: this.removeStatus is not a function
Run Code Online (Sandbox Code Playgroud)

编辑1:我已经添加了实际的代码,因为你可以看到我在构造函数中绑定了validateEmail

class Email extends React.Component {
constructor(props) {
      super(props);
      this.change = this.change.bind(this);
      this.validateEmail = this.validateEmail.bind(this);
      this.state = {
        value : ''
      }
    }
removeStatus() {
$('input').on('keydown',function () {
    $('.contextual-info').fadeOut();
});
}

 validateEmail(event) {
event.preventDefault();
var token = $('#token').val();
var email_regex=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if ($.trim(this.state.value)  !== "") {
    if (email_regex.test(this.state.value)) {
        $.ajax({
            url:'/login',
            type:'post',
            data:{email:this.state.value,_token:token},
            success: function (response) {
            if (response) {
                $('#email').remove();
                $('.btn').remove();
                $('#status').html('');
                ReactDOM.render(<Password /> ,document.getElementById('login-dialogue'));
                $('input[type="password"]').focus();
                }  else {
                $('input#email').addClass('input-context');
                if($('#status').html('<div class="bg-danger contextual-info wrong">Email Address Not Found!</p>')){
                    this.removeStatus();
                    }
                }
            }
        });
    } else {
    if($('#status').html('<div class="bg-danger contextual-info wrong">Invalid Email Address</div>')){
        this.removeStatus();
    }
    }
} else {
    if($('#status').html('<div class="bg-danger contextual-info wrong">Can\'t submit an empty field!</div>')){
        this.removeStatus();
    }
}
}
change (event) {
this.setState({
    value : event.target.value
    });
}

render(){
    return(
        <div className="login-dialogue" id="login-dialogue">
        <h1 className="text-center">Log in</h1>
        <div id="status"></div>
        <form action="" onSubmit={this.validateEmail} id="validateEmail">
        <input type="email" id="email" value={this.state.value} placeholder="Email Address" onChange={this.change} />
        <button type="submit" className="btn btn-flat btn-wide teal white-text">Continue</button>
        </form>
        </div>
        );
}

}
 ReactDOM.render(<Email /> ,document.getElementById('flex-me'));
Run Code Online (Sandbox Code Playgroud)

joe*_*ews 14

您的方法已正确定义,因此问题在于您的调用方式 validateEmail.

您以一种设置thisSomething实例以外的方式调用它.这在事件监听器中很常见.我想你的代码中有这样的代码render:

<button onClick={this.validateEmail} /> 
Run Code Online (Sandbox Code Playgroud)

React 的推荐解决方案是在构造函数中绑定事件处理程序:

class Something extends React.Component {

  constructor() {
    super();
    this.validateEmail = this.validateEmail.bind(this);
  }

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

您也可以从箭头函数内部调用该方法,该函数保留this声明它的位置的值:

<button onClick={() => this.validateEmail()} /> 
Run Code Online (Sandbox Code Playgroud)

这种方法的缺点onClick是每次渲染组件时都会创建一个新的处理程序.


编辑:同样的问题,不同的地方.你removeStatus在里面打电话function,失去外部this绑定.使用箭头功能代替:

$.ajax({
  success: (response) => { 
    // etc
    this.removeStatus();
  }
})
Run Code Online (Sandbox Code Playgroud)

进一步阅读: