使用 useRef 或 createRef

问题描述

我想通过按下按钮将 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 用于函数组件,卸载时会丢失引用。