ReactNative Animated.ScrollView ref TypeScript 定义

时间:2021-04-18 01:43:10

标签: typescript react-native

在 React Native 组件中,我有:<Animated.ScrollView ref={cardRef} ... />

当我将鼠标悬停在 ref 顶部时,我看到 (JSX attribute) React.ClassAttributes<Animated.ScrollView>.ref?: React.LegacyRef<Animated.ScrollView> | undefined,因此我像这样创建了 const cardRef = useRef<React.RefObject<Animated.ScrollView> | undefined>(undefined);,但是执行 cardRef.current?.scrollTo({ x: newOffset }); 会给我警告 {{1} }:scrollTo

我怎么知道正确的 TS 定义应该是什么?有没有办法或者总是猜谜游戏?

1 个答案:

答案 0 :(得分:1)

几乎就在那里。 useRef 上的泛型类型参数用于这是引用的类型。换句话说,.current 属性的类型。您不需要在泛型中包含 RefObject,因为它已经知道它创建了一个 RefObject。它只需要知道它正在创建的 RefObject 是什么类型

您当前的类型表示它正在创建一个 RefObject,其 .current 属性是 RefObject,而 ref 的 .current 属性是 ScrollView。< /p>

通过查看类型声明和检查错误消息,您会发现一个小技巧,即 null 是任何元素引用的可接受值。因此,您可以使用 null 作为初始值,而不必在类型中包含 | undefined

你应该改变:

const cardRef = useRef<React.RefObject<Animated.ScrollView> | undefined>(undefined);

到:

const cardRef = useRef<Animated.ScrollView>(null);