表单 in React
Controlled and uncontrolled 输入, 表单 validation, and handling 表单 submission.
你将学到
- Controlled 组件 and two-方式数据 binding
- Handling 多个输入使用单个状态对象
- 表单 validation 模式 and 错误 display
- difference 之间 controlled and uncontrolled 输入
概念讲解
Controlled Components
In React, a controlled component is an input whose value is controlled by React state. The input's 值 is set from state, and every keystroke updates the state via onChange. This creates a single source of truth — the state drives the input, and the input updates the state. This circular flow gives you full control: you can validate, transform, or block input on every keystroke. Controlled inputs are the recommended pattern in React.
Handling Multiple Inputs
When a form has many fields, creating a separate state variable for each is tedious. Instead, use a single state object and a shared change handler that updates the field by name. Use the input's name attribute to identify which field changed: setForm(prev => ({ ...prev, [e.目标.name]: e.目标.值 })). This computed property name pattern keeps your handler DRY regardless of how many fields the form has.
Form Validation
Validation can happen on every change (real-time) or on submit. For real-time validation, check the field value in the onChange handler or in a derived variable. Store errors in a separate state object and display them next to the relevant fields. For submit-time validation, validate all fields in the onSubmit handler before proceeding. Libraries like react-Hook-表单 and zod can simplify complex validation, but for simple forms, manual validation is sufficient.
Uncontrolled Inputs
An uncontrolled input manages its own state in the DOM, and you read its value via a ref when needed (e.g., on submit). This is closer to traditional HTML form behavior. Uncontrolled inputs are simpler for one-time reads but harder to validate in real time. Use them for simple forms or when integrating with non-React code. For most cases, controlled inputs are preferred because they give you full control over the data flow.
Form Libraries
For complex forms with many fields, nested validation, or dynamic field arrays, consider a form library. react-Hook-表单 is performant and minimizes re-renders. Formik is a popular, well-documented alternative. Pair them with a validation schema library like zod or yup for declarative validation rules. These tools handle the boilerplate of field registration, validation, error messaging, and submission so you can focus on the form logic.
示例代码
import { useState } from "react";
function RegistrationForm() {
const [form, setForm] = useState({ username: "", email: "", password: "" });
const [errors, setErrors] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setForm(prev => ({ ...prev, [name]: value }));
};
const validate = () => {
const errs = {};
if (!form.username) errs.username = "Username is required";
if (!form.email.includes("@")) errs.email = "Valid email required";
if (form.password.length < 8) errs.password = "Min 8 characters";
return errs;
};
const handleSubmit = (e) => {
e.preventDefault();
const errs = validate();
setErrors(errs);
if (Object.keys(errs).length === 0) {
console.log("Submitting:", form);
}
};
return (
<form onSubmit={handleSubmit}>
<input name="username" value={form.username} onChange={handleChange} />
{errors.username && <span className="error">{errors.username}</span>}
<input name="email" value={form.email} onChange={handleChange} />
{errors.email && <span className="error">{errors.email}</span>}
<input name="password" type="password" value={form.password} onChange={handleChange} />
{errors.password && <span className="error">{errors.password}</span>}
<button type="submit">Register</button>
</form>
);
}
单个状态对象持有所有字段. shared handleChange uses computed 属性 names. Validation 运行 on 提交 and 错误 display inline.
动手试一试
- Regex Tester
构建 and 测试 regex 模式 for email, 密码, and phone validation.
- JSON Formatter
Inspect 表单数据 as JSON 之前发送它 到 API.
常见错误
错误写法
Forgetting 到设置值 prop on controlled 输入
正确做法
controlled 输入必须有 两者都值={状态} and onChange={处理函数}. 不使用值, 输入是 uncontrolled and React cannot control 它. 不使用 onChange, 输入 becomes 读取-仅.
错误写法
创建 separate useState calls for 每个表单字段
正确做法
Use one 状态对象 and shared 处理函数使用 computed 属性 names: setForm(prev => ({ ...prev, [name]: 值 })). 这个 scales 到任何数字的 字段.
练习 表单 in React
6 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。