【发布时间】:2022-01-08 11:58:33
【问题描述】:
我在视图上使用 ref。打字稿给我一个错误“对象可能是‘空’”。视图上使用的 ref 的正确类型是什么?具体来说,我使用的是Animated.View,但我认为这没有什么不同。
此处的其他答案适用于 ReactJS(web) 并使用 const overlayEl = useRef<HTMLDivElement>(null);,但我正在寻找 React Native 的答案。
const Component = () => {
const ref = React.useRef(null);
React.useLayoutEffect(()=>{
console.log(ref.current.clientHeight);
// ^ Error: "Object is possibly null" on the `ref.current` portion
},[]);
return (
<Animated.View ref={ref} style={{height: 100}}></Animated.View>
);
}
我尝试过的事情:
const ref = React.useRef<React.FunctionComponent>(null);
const ref = React.useRef<React.ReactElement>(null);
const ref = React.useRef<React.MutableRefObject<null>>(null);
const ref = React.useRef(null) as React.MutableRefObject<null>;
console.log(ref?.current?.clientHeight);
// ^ Error: Property clientHeight does not exist on type 'never'
唯一有效的是这个,但这并不是真正的正确修复
React.useLayoutEffect(()=>{
const current = ref?.current || { clientHeight: 0 };
console.log(ref.current.clientHeight);
},[]);
【问题讨论】:
-
唯一有效的是这个,但这并不是真正的正确修复你认为什么是正确的修复?
-
如果有办法通过在 useRef 声明中正确设置类型来解决它,那么对我来说,这是正确的解决方法。我想我根本不知道正确的类型是什么。如果没有打字来解决它,那么我想我上面写的就是正确的解决方法。
-
好吧
useRef(null)有效地返回一个具有null当前属性的 ref,TypeScript 在执行代码之前会警告您,因此您必须使用空检查或可选的链接运算符对其进行调整就像你做的那样 -
我明白了。并且将
useRef()不带 null 并没有什么区别,因为它仍然是未定义的。如果您对此做出回应,我可以接受您的评论作为答案。谢谢 -
useLayoutEffect在渲染之前运行,这就是您的 ref 为空的原因。有什么理由使用React.useLayoutEffect而不是React.useEffect
标签: typescript react-native typescript-typings