React Form Component onSubmit Handler Not Working

后端 未结 4 751
滥情空心
滥情空心 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: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(
          
    ); } }

    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 =>.

提交回复
热议问题