导航


HTML

CSS

JavaScript

浏览器 & 网络

版本管理

框架

构建工具

TypeScript

性能优化

软实力

算法

UI、组件库

Node

业务技能

针对性攻坚

AI


🔥 受控组件

function ControlledInput() {
  const [value, setValue] = React.useState('');

  return (
    <input
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />
  );
}

发生了什么?

input 自己不“记值”

多个表单的受控写法

function Form() {
  const [form, setForm] = React.useState({
    username: '',
    password: '',
  });

  return (
    <>
      <input
        value={form.username}
        onChange={(e) =>
          setForm({ ...form, username: e.target.value })
        }
      />
      <input
        type="password"
        value={form.password}
        onChange={(e) =>
          setForm({ ...form, password: e.target.value })
        }
      />
    </>
  );
}

非受控组件

方法一

方法二(hooks)

function UncontrolledInput() {
  const inputRef = React.useRef<HTMLInputElement>(null);

  const handleSubmit = () => {
    console.log(inputRef.current?.value);
  };

  return (
    <>
      <input ref={inputRef} defaultValue="hello" />
      <button onClick={handleSubmit}>提交</button>
    </>
  );
}

如何选择

✅ 优先用受控组件

✅ 非受控更合适