我正在使用反应和打字稿。我想获得 div 标签的高度,所以我使用了 useRef。但是,我在当前收到 ts 错误。
Property 'current' is not present in type 'never'. ts(2339)
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (ref != null || ref.current != null) {
setHeight(ref.current.clientHeight);
}
}, [user]);
ref.current != null
如果ref != null
为真,您的条件将“永远不会”为真我可以在您的逻辑中看到,您正在尝试ref.current
在引用之前检查是否为空ref.current.clientHeight
所以正确的条件应该是:
useEffect(() => {
if (ref !== null && ref.current !== null) {
setHeight(ref.current.clientHeight);
}
}, [user]);
该||
条件运行由左到右,如果你想用你的条件,那么为了改变保持:
useEffect(() => {
if (ref.current !== null || ref !== null) {
setHeight(ref.current.clientHeight);
}
}, [user]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句