react form implementation

controlled components

In HTML, form elements such as form elements (such as <input><textarea> and  ) usually maintain their own state and update based on user input. <select>In React, mutable state is usually stored in the component's state property and can only be  updated using setState() .
We can combine the two and make React's state the "sole data source". The React component that renders the form also controls what happens to the form during user input. Form input elements whose values ​​are controlled by React in this way are called "controlled components".
Of course, the implementation of obtaining form values ​​is flexible.

class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    //保存表单的值
    this.state = {
      username: '默认用户名',
      exp: '0'
    }
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(e){
    // 阻止默认提交行为
    e.preventDefault();
    // 获取表单内容
    console.log(this.state);
  }
  handleInputChange(inputName,e){
    this.setState({
      [inputName]: e.target.value
    })
  }
  render(){
    return (
      <div>
        <form action="/abc" onSubmit={this.handleSubmit}>
          姓名: <input type="text" name="username" value={this.state.username} onChange={e=> this.handleInputChange('username',e)}/><br/>
          经验: <select name="exp" value={this.state.exp} onChange={e=> this.handleInputChange('exp',e)}>
          <option value="0">无</option>
          <option value="1">1-3年</option>
          <option value="2">3-5年</option>
          </select>
          <input type="submit" value="提交" />
        </form>
      </div>
    )
  }
}
// 通过调用React自身方法render可以得到当前组件的实例对象,并渲染到页面容器.
ReactDOM.render(<HelloWorld />,document.getElementById('root'));

 

Guess you like

Origin blog.csdn.net/m0_67388537/article/details/131954994