使用 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 用于函数组件,卸载时会丢失引用。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...