表单上的ReactSubmit函数不起作用

时间:2019-07-27 08:07:16

标签: reactjs

我不确定我在做什么错。当我使用onSubmit函数单击表单元素上的按钮时,我试图控制台日志。

export class Search extends Component {
  state = {
    text: ''
  };

  onFormSubmit = e => {
    console.log('Working');
    e.preventDefault();
  };

  onChange = e => this.setState({ [e.target.name]: e.target.value });

  render() {
    return (
      <div>
        <form onSubmit={this.onFormSubmit} className='form' />
        <input
          type='text'
          onChange={this.onChange}
          value={this.state.text}
          name='text'
          placeholder='Search Users...'
        />
        <input
          type='submit'
          value='Search'
          className='btn btn-dark btn-block'
        />
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

您不是将按钮包装在form中,而是关闭form本身,

 <form onSubmit={this.onFormSubmit} className='form' />

您需要将inputbutton包裹在form中,

<form onSubmit={this.onFormSubmit} className='form'>
   <input
       type='text'
       onChange={this.onChange}
       value={this.state.text}
       name='text'
       placeholder='Search Users...'
   />
   <input
      type='submit'
      value='Search'
      className='btn btn-dark btn-block'
   />
</form> //form closing tag