React Form Component onSubmit Handler Not Working

后端 未结 4 757
滥情空心
滥情空心 2021-02-07 14:04

I have the following React component:

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

           


        
相关标签:
4条回答
  • 2021-02-07 14:07

    For me, it was because the form didn't have an action property set.

    <form onSubmit={this.handleSubmit} action="#">
            <input placeholder="githug login" ref="login" />
            <button>Add Login</button>
          </form>
    
    0 讨论(0)
  • 2021-02-07 14:17

    One obvious piece of information: do not forget to include your button inside the <form>. I got stuck for a while until I figured out I had put my submit button outside my form, like this:

      <form onSubmit={ this.handleSubmit }>
        <input placeholder="githug login" ref="login" />
      </form>            
      <button type="submit">Add Login</button>
    

    hence the onSubmit event was not being called, and would never be.

    0 讨论(0)
  • 2021-02-07 14:21

    When you use React with ES2015 classes you should set this to event handlers

    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

    Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.

    0 讨论(0)
  • 2021-02-07 14:31

    You need to use button or input with type="submit"

    <button type="submit">Submit</button>
    

    Or

    <input type="submit" value="Submit" />
    
    0 讨论(0)
提交回复
热议问题