reactjs - 平面列表 - ScrollToIndex 应与 getItemLayout 或 onScrollToIndexFailed 结合使用

标签 reactjs react-native

setTimeout(() => { this.myFlatList.scrollToIndex({animated:true , index: 100}) }, 100);  

enter image description here

如果我在平面列表中使用scrolltoindex,则会返回此错误;

scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed

我尝试使用 getItemLayout 但我的平面列表项目具有不同的高度,我该如何解决此问题?

getItemLayout={(data, index) => (
                {length: 40, offset: 40 * index, index}
              )}

最佳答案

我在显示图像的水平列表中遇到了类似的错误,按下时所选图像应显示在轮播中。

我通过使用initialScrollIndexFlatList上设置选定的索引来解决这个问题。当 initialScrollIndex 无法显示正确图像时,我还使用 onScrollToIndexFailed 滚动到正确的图像。

这是通过设置 500 毫秒的超时然后滚动到所选图像来完成的。

完整示例(仅包含有关此错误的 Prop ):

const flatList = useRef<FlatList>(null);

...

<FlatList
  ref={flatList}
  initialScrollIndex={props.activeIndex}  
  onScrollToIndexFailed={info => {
    const wait = new Promise(resolve => setTimeout(resolve, 500));
    wait.then(() => {
      flatList.current?.scrollToIndex({ index: info.index, animated: true });
    });
  }}
/>

关于reactjs - 平面列表 - ScrollToIndex 应与 getItemLayout 或 onScrollToIndexFailed 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53059609/

相关文章:

reactjs - 从错误的目录 react 导入

javascript - 如何在响应中使用错误边界?

javascript - 如何在 React 中迭代 JSON 数据并动态创建和填充组件?

javascript - 检测 audio.play() 何时完成

android - 世博会的 SocketTimeOutException

javascript - Android v3.3.0 variant.getMegrate() 已过时并替换为 variant.getMergeAssetsProvider()

android - 在 React Native 中的现有状态转换期间(例如在 `render` 内)无法更新

javascript - 我想调用另一个组件的方法

javascript - 类型错误 : Cannot read property 'map' of null

reactjs - TabNavigator 涵盖内容