小编典典

React Form组件onSubmit处理程序不起作用

reactjs

我有以下React组件:

class Form extends React.Component {
  handleSubmit(e) {
    e.preventDefault();

    let loginInput = ReactDOM.findDOMNode(this.refs.login);

    // change Main component's state
    this.props.addCard(loginInput.value);

    // reset the form
    loginInput.value = '';
  }

  render() {
    return(
      <form onSubmit={this.handleSubmit}>
        <input placeholder="githug login" ref="login" />
        <button>Add Login</button>
      </form>
    );
  }
}

如您所见,我希望在handleSubmit提交表单时都调用该函数。我已通过将函数添加到onSubmit处理程序来表明这一点。

该函数在正确的时间被调用。但是,该this函数内的值为null。这让我感到惊讶,因为我期望thisReact组件的价值。thisnull
的事实令我感到惊讶,因为我使用的是非常相似的逻辑/代码,如官方的React文档所建议的那样。

我将不胜感激,帮助您弄清为什么thisReact组件不是预期的,以及如何修复代码。


阅读 619

收藏
2020-07-22

共1个答案

小编典典

React与之一起使用时,ES2015 classes应设置this事件处理程序

class Form extends React.Component {
  constructor(props) {
     super(props);
     this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();

    let loginInput = this.refs.login;
    this.props.addCard(loginInput.value);
    loginInput.value = '';
  }

  render() {
    return(
      <form onSubmit={ this.handleSubmit }>
        <input placeholder="githug login" ref="login" />
        <button>Add Login</button>
      </form>
    );
  }
}

Example

No Autobinding

方法遵循与常规ES6类相同的语义,这意味着它们不会自动将其绑定到实例。您必须显式使用.bind(this)或箭头函数=>。

2020-07-22