我刚开始使用 React Hook 引用。我遵循了几个代码示例,所有示例都引用 useRef
但代码根本不起作用。然而,当我将其更改为 createRef
时,它就完美地工作了。因此我很好奇这两个函数有什么区别?
// Near the top of my component
let companyNameRef = React.createRef();
// A useEffect added simply to give focus to a particular input element the first time the component is loaded
useEffect(() => {
if (companyNameRef.current) {
companyNameRef.current.focus();
}
}, [companyNameRef]);
// Within the input element
<Form.Control name='companyName'
as='input'
onChange={e => handleChange(e)}
ref={companyNameRef}
/>
如果我将 createRef()
更改为 useRef()
或 useRef(null)
或 useRef('')
初始焦点功能停止工作。
有人知道为什么吗?
最佳答案
createRef
旨在在 React 类组件中用于捕获 DOM 句柄。
useRef
旨在在 React 函数组件中使用,不仅用于捕获 DOM 句柄,还可以作为模拟类组件中的类成员变量的持久存储。
在您的代码(我假设属于 React.FunctionComponent
)中尝试设置 let companyNameRef = useRef(null);
并提供一个空数组,例如[]
到 useEffect
作为第二个参数,以确保仅在初始渲染时调用它。
关于javascript - React.createRef 和 React.useRef 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57949780/