问题描述
我想通过按下按钮将 const [solution, setSolution] = useState(0);
设置为输入元素的值
I want to set the const [solution, setSolution] = useState(0);
with the value of a input element by pressing a button
我使用 createRef
或使用 useRef
钩子获得相同的结果
I get the same result using createRef
or using the useRef
hook
reading What's the difference between useRef
and createRef
?
给出了不同的答案,你到底要做什么,你对方法有明确的内在吗?
gives quit different answers what exactly thees to do, is there a clear inside about thees to methods ?
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
用于类组件,在函数组件的上下文中调用它会视为正常函数,因此将在每次渲染时重新初始化您的参考.
createRef
is for class components, calling it in a context of function component will be treated as a normal function, hence will RE-INITIAL your reference on every render.
useRef
用于函数组件,卸载时会丢失引用.
useRef
is for function components, you lose your ref on unmount.
这篇关于使用 useRef 或 createRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!