【问题标题】:FlatList scrollToIndex using useRef with Typescript - Type ErrorFlatList scrollToIndex 使用 useRef 和 Typescript - 类型错误
【发布时间】:2021-11-13 15:50:15
【问题描述】:

我正在使用 FlatList,我想创建一个 ref 以便在按下一个按钮时能够滚动 FlatList。

问题是我正在使用 Typescript,但我遇到了一种我无法解决的类型错误。

问题是,如何为 FlatList ref 创建接口?

我们有一个我正在做的例子。

let flatListRef = useRef();

<FlatList
  ref={flatListRef} // Error Here
  data={store.data}
  ... />

<Button 
  onPress={() =>
    flatListRef.current.scrollToIndex({index:index})
  } />

我遇到的类型错误是我将 ref 设置到 FlatList 中时

错误提示:

重载 1 of 2, '(props: FlatListProps |只读>): FlatList<...>',给出了以下错误。 类型 'MutableRefObject' 不可分配给类型 'LegacyRef> | 不明确的'。 类型 'MutableRefObject' 不可分配给类型 'RefObject>'。 属性“当前”的类型不兼容。 类型 'undefined' 不能分配给类型 'FlatList |空'。

重载 2 of 2, '(props: FlatListProps,上下文:任何):FlatList',给出以下错误。 类型 'MutableRefObject' 不可分配给类型 'LegacyRef> | 未定义'。

当我在创建它时将类型设置为 ref 时,错误没有解决,例如:

interface ListProps {
  data: string;
  type: number;
  id: number;
 }

let flatListRef = useRef<ListProps>()

或者我需要在创建 useRef 钩子时将数据结构或其他东西作为 initialValue 传递吗?

【问题讨论】:

    标签: reactjs typescript react-native react-hooks


    【解决方案1】:

    您的 flatListRefrefFlatList 实例。这就是您想要用作泛型类型参数的内容。

    对 DOM 元素的引用期望初始值为 null 而不是 undefined,因此您还需要修复它。

    const flatListRef = useRef<FlatList>(null);
    

    当您访问 ref 时,您需要使用可选链 ?.,以防万一 .current 仍然是 null

    flatListRef.current?.scrollToIndex({index})
    

    TypeScript Playground Link

    【讨论】:

    • 这正是我想要的。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2021-02-06
    • 2021-04-29
    • 1970-01-01
    • 2020-01-01
    • 2020-04-06
    • 1970-01-01
    相关资源
    最近更新 更多