【发布时间】:2020-01-16 20:58:06
【问题描述】:
我是使用 React Hook refs 的新手。我遵循了几个代码示例,它们都引用了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(''),则初始焦点功能将停止工作。
有人知道为什么吗?
【问题讨论】:
-
尝试向
useEffect提供空的依赖数组。 -
两者都为我工作
标签: javascript reactjs react-hooks