Trí*_*han 5 javascript reactjs react-ref react-hooks
我有这个
const CompA = () => {
let _input;
return (
<input ref={el => _input = el} type="text" />
);
}
Run Code Online (Sandbox Code Playgroud)
和这个
const CompB = () => {
const _input = useRef(null);
return (
<input ref={_input} type="text" />
);
}
Run Code Online (Sandbox Code Playgroud)
二_input
是input
标签的 ref 对象,我找不到它们之间的差异。
我的问题是:两者之间有什么区别_input
,哪个_input
更好?
定义 refs 的两种方式是不等价的。
考虑第一个例子
const CompA = () => {
let _input;
return (
<input ref={el => _input = el} type="text" />
);
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,每当 CompA 重新渲染,因为新变量_input
被创建,例如,如果你在 CompA 中有一个 useEffect 打算在初始渲染时运行,并且它使用这个 ref 变量每隔一段时间执行一些东西,它会导致不一致.
现在考虑第二种情况
const CompA = () => {
const _input = useRef(null);
return (
<input ref={_input} type="text" />
);
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,即使 _input 变量是在每次渲染时创建的,也要useRef
确保它收到与第一次收到的相同的引用,并且不会再次初始化它。useRef
是定义 refs 的正确方法functional Components
。对于您可以使用的类组件createRef
或您提到的回调模式
归档时间: |
|
查看次数: |
2350 次 |
最近记录: |