问题描述
我想通过按下按钮将 const [solution,setSolution] = useState(0);
设置为输入元素的值
我使用 createRef
或使用 useRef
钩子得到相同的结果
阅读What's the difference between useRef
and createRef
?
function Interface() {
const [solution,setSolution] = useState(0);
const solutionInp = useRef();
// --createRef();
const onButtonClick = () => {
// `current` points to the mounted text input element
setSolution( solutionInp.current.value)
};
return (
<input
type="text"
// value={solution}
ref={solutionInp}
// onInput={(e) => setSolution(e.target.value)}
/>
</section>
<button type="button" onClick={onButtonClick}>do</button>
)}
解决方法
createRef
用于类组件,在函数组件的上下文中调用它将被视为普通函数,因此将重新-初始您在每次渲染时的参考。
useRef
用于函数组件,卸载时会丢失引用。