Skip to content

Uncontrolled 组件

一句话解释

uncontrolled 组件是 表单输入哪里 DOM 持有值, and React 读取它 通过 ref — 典型地 on 提交.

用大白话说

uncontrolled 输入 lets DOM manage 值. 你 don't bind value 到状态 — 相反, 你 use ref 到读取值 当你 需要它 (通常 on 表单提交). 你能 设置默认使用 defaultValue prop.

const inputRef = useRef() ... <input ref={inputRef} /> ... inputRef.current.value gives you the text. This is closer to traditional HTML form behavior.

Uncontrolled inputs are simpler for forms where you only need the value on submit and don't need real-time validation or transformation. But they are less React-idiomatic and harder to integrate with validation libraries. Most React forms use controlled components.

示例

jsx
function NameForm() {
  const inputRef = useRef(null);

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(inputRef.current.value); // read on submit
  };

  return (
    <form onSubmit={handleSubmit}>
      <input ref={inputRef} defaultValue="Alice" />
      <button type="submit">Submit</button>
    </form>
  );
}

输入's 值 lives in DOM. ref gives access 到它 on 提交. defaultValue 设置初始文本不使用 controlling 它.

相关术语

相关资源

相关课程

  • 表单

    学习 uncontrolled 输入 and 当到 use 它们.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表