在React.js中使用表单

在简单的html表单中,表单元素在内部保持其值,并在表单提交按钮上提交。

示例

<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<form>
   <label>
      User Name:
      <input type="text" name="username" />
   </label>
   <input type="submit" value="Submit Form" />
</form>
</body>
</html>

在上面的示例中,我们有一个名为username的简单输入,我们可以在表单提交时接收其值。html表单的默认行为是导航到新页面,即发布表单提交页面。

但是,如果我们有一个表单提交处理程序JavaScript函数也可以验证表单数据,则可以提供更多优势。验证将向用户提供相关反馈。

React有一种处理表单提交的技术,称为受控组件。

与html中一样,input,textarea等元素保留其自身的状态并根据用户操作进行更新。在React中,可变字段与状态对象一起保存。

在React的受控组件方法中处理用户名字段-

class UserForm extends React.Component {
   constructor(props) {
      super(props);
      this.state = {username: ''};
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
   }
   handleChange(event) {
      this.setState({username: event.target.value});
   }
   handleFormSubmit(event) {
      console.log('username: ' + this.state.username);
      event.preventDefault();
   }
   render() {
      return (
         <form onSubmit={this.handleFormSubmit}>
            <label>
               Name:
               <input type="text" value={this.state.username} onChange={this.handleUsernameChange} />
            </label>
            <input type="submit" value="Submit" />
         </form>
      );
   }
}

这里我们有onChange处理函数,用于更新状态字段用户名。

在formSubmit上,我们仅在浏览器中显示控制台日志以显示提交的用户名。

组件的其他受控类型是文本区域,选择标签,单选按钮等。

还有一些不受控制的组件,例如文件类型,它们本质上是只读的,并且仅在表单提交时才有值。

使用单个JS函数处理多个表单输入-

handleInputChange(event) {
   const value = event.target.value;
   const name = event.target.name;
   this.setState({
      [name]: value
   });
}

应该通过使用状态启动为字段提供默认值来避免使用字段值为空的受控输入。

对于React中表单处理的全面解决方案,可以使用诸如formik之类的第三方库来完成。使用验证,向用户反馈以及其他功能非常简单。