导航
定义
数据流方向只有一个
React state → 表单 value → onChange → setState → React state
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 })
}
/>
</>
);
}
ref="xxxRef"this.refs.xxxRef 访问
this.refs.xxxRef.valuexxxRef = React.useRef()ref={ xxxRef }xxxRef.current.value 获取值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>
</>
);
}