react表单实现

受控组件

在 HTML 中,表单元素(如<input>、 <textarea> 和 <select>)之类的表单元素通常自己维护 state,并根据用户输入进行更新。而在 React 中,可变状态(mutable state)通常保存在组件的 state 属性中,并且只能通过使用 setState()来更新。
我们可以把两者结合起来,使 React 的 state 成为“唯一数据源”。渲染表单的 React 组件还控制着用户输入过程中表单发生的操作。被 React 以这种方式控制取值的表单输入元素就叫做“受控组件”。
当然获取表单值的实现方式是灵活的.

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'));

猜你喜欢

转载自blog.csdn.net/m0_67388537/article/details/131954994
今日推荐