首页 > 解决方案 > React-Native:使用 FlatList ref 的 scrollToIndex 时出错

问题描述

我正在尝试滚动到 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,
});

标签: reactjsreact-nativereact-native-flatlistscrolltoindex

解决方案


试试这个添加 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 repo :: https://github.com/facebook/react-native/issues/14198


推荐阅读