React Form Component onSubmit Handler Not Working

后端 未结 4 1355
不思量自难忘°
不思量自难忘° 2021-02-07 13:29

I have the following React component:

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

           


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 14:06

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

提交回复
热议问题