3

我正在使用 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<{ data: string; type: number; id: number; }> | Readonly<FlatListProps<{ data: string; type: number; id: number; }>>): FlatList <...>',给出以下错误。类型 'MutableRefObject' 不可分配给类型 'LegacyRef<FlatList<{ data: string; 类型:数字;身份证号码; }>> | 不明确的'。类型 'MutableRefObject' 不可分配给类型 'RefObject<FlatList<{ data: string; 类型:数字;身份证号码; }>>'。属性“当前”的类型不兼容。类型 'undefined' 不能分配给类型 'FlatList<{ data: string; 类型:数字;身份证号码; }> | 空值'。

重载 2 of 2, '(props: FlatListProps<{ data: string; type: number; id: number; }>, context: any): FlatList<{ data: string; 类型:数字;身份证号码; }>',给出以下错误。类型 'MutableRefObject' 不可分配给类型 'LegacyRef<FlatList<{ data: string; 类型:数字;身份证号码; }>> | 不明确的'。

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

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

let flatListRef = useRef<ListProps>()

还是在创建 useRef 挂钩时需要将数据结构或其他内容作为 initialValue 传递?

4

1 回答 1

8

flatListRefref一个FlatList实例。这就是您想要用作泛型类型参数的内容。

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

const flatListRef = useRef<FlatList>(null);

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

flatListRef.current?.scrollToIndex({index})

TypeScript Playground 链接

于 2021-09-19T22:40:53.677 回答