Controlled 组件
一句话解释
controlled 组件是 表单输入谁的值 是 controlled 通过 React 状态 — 输入总是 reflects 状态, and 更改更新状态.
用大白话说
controlled 输入是 one 哪里 React 状态是 "单个源的 truth" for 输入's 值. 你设置 value={state} and onChange={(e) => setState(e.target.value)}. The input always shows the current state, and every keystroke flows through React.
This makes form data immediately available in your component for validation, formatting, or conditional UI. You can transform the value on input (e.g., uppercase), prevent invalid characters, or disable submission based on the current value.
The alternative is an uncontrolled component, where the DOM itself holds the value and you read it with a ref on submit. Controlled components are the React-idiomatic approach and are recommended for most forms.
示例
function NameForm() {
const [name, setName] = useState("");
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}
// `name` always equals the input's current value.输入's 值是 边界到 状态. 每个 keystroke 更新状态, and 输入 re-渲染使用新 值 — 它们是 总是 in sync.
常见混淆
容易混淆的对象: uncontrolled 组件
关键区别: controlled 组件's 值 comes 从 React 状态. uncontrolled 组件's 值 lives in DOM and 是读取通过 ref. Controlled 是 React-idiomatic; uncontrolled 是 simpler for 基础 one-时间-读取表单.
相关术语
相关资源
相关课程
- 表单
学习 controlled 输入 and 表单 handling.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。