使用 useRef 或 createRef

IT技术 javascript reactjs react-hooks virtual-dom
2021-05-03 10:49:55

我想const [solution, setSolution] = useState(0); 通过按下按钮来设置输入元素的值

我使用createRef或使用useRef钩子得到相同的结果

阅读和 和有什么区别useRefcreateRef

给出了不同的答案,你到底要做什么,对方法有明确的内部说明吗?

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>
)}


1个回答

createRef对于类组件,在函数组件的上下文中调用它会被视为普通函数,因此将在每次渲染时重新初始化您的引用。

useRef对于功能组件,您会在卸载生命周期中丢失您的引用。