简体   繁体   English

使用 useRef 或 createRef

[英]using useRef or createRef

I want to set the const [solution, setSolution] = useState(0);我想设置const [solution, setSolution] = useState(0); with the value of a input element by pressing a button通过按下按钮来获取输入元素的值

I get the same result using createRef or using the useRef hook我使用createRef或使用useRef钩子得到了相同的结果

reading What's the difference between useRef and createRef ?阅读useRefcreateRef有什么区别?

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 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. createRef用于class 组件,在 function 组件的上下文中调用它将被视为普通 function ,因此将在每次渲染时重新初始化您的参考。

useRef is for function components , you lose your ref on unmount. useRef用于function 组件,卸载时会丢失参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM