小编典典

我如何在React类Es6中的另一个方法中调用一个方法

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

 }
}

由于某种原因,它无法正常工作。在我的Javascript控制台(Chrome浏览器)中

login.js:132Uncaught TypeError: this.removeStatus is not a function

编辑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'));

阅读 688

收藏
2020-07-22

共1个答案

小编典典

您的方法已正确定义,因此问题出在如何 调用上 validateEmail

您以一种设置thisSomething实例以外的方式调用它。这在事件侦听器中很常见。我想您的代码中有一些类似的代码render

<button onClick={this.validateEmail} />

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

class Something extends React.Component {

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

  // ...
}

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

<button onClick={() => this.validateEmail()} />

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


编辑 :同一问题,不同的地方。您removeStatus在内部调用function,这会失去外部this绑定。改用箭头功能:

$.ajax({
  success: (response) => { 
    // etc
    this.removeStatus();
  }
})

进一步阅读:

2020-07-22