React-Native:使用 FlatList ref 滚动到索引时出错

React-Native: Getting an error when scrollToIndex using FlatList ref

我正在尝试滚动到 flatlist 上的特定索引。我正在使用它的水平属性。我正在尝试使用 ref 滚动到特定索引。但是我遇到了以下错误。

scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed, otherwise there is no way to know the location of offscreen indices or handle failures.

这是我的 Flatlist 代码:

<FlatList
     ref={flatRef}
     showsHorizontalScrollIndicator={false}
     horizontal
     data={data}
     renderItem={renderCell}
   />

这是在特定索引上滚动的代码:

flatRef.current.scrollToIndex({
  animated: false,
  index: index,
  viewPosition: 0.5,
});

关注这个:

Flat List - ScrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed

按照上一期的描述添加onScrollToIndexFailed prop

试试这个添加 onScrollToIndexFailed 函数

<FlatList
  ref={fListRef}
  onScrollToIndexFailed={info => {
    const wait = new Promise(resolve => setTimeout(resolve, 700));
    wait.then(() => {
      fListRef.current?.scrollToIndex({ index: info.index, animated: true/false });
    });
  }}
/>

您也可以查看 git 存储库 :: https://github.com/facebook/react-native/issues/14198