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

时间:2018-10-30 07:49:57

标签: reactjs react-native

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

enter image description here

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

  

scrollToIndex应该与getItemLayout或   onScrollToIndexFailed

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

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

3 个答案:

答案 0 :(得分:7)

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

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

这是通过将超时时间设置为500ms,然后滚动到选定的图像来完成的。

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

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 });
    });
  }}
/>

答案 1 :(得分:2)

我遇到了类似的问题,并通过在initialNumToRender中更改了FlatList来解决了这个问题。

此道具定义要渲染的组件数量。如果滚动到未渲染的索引,则会显示错误。

React Native initialNumToRender的默认值为 10 ,我更改为initialNumToRender={60}。如果您的列表更大或更小,则需要更改此数字。

答案 2 :(得分:1)

建议的解决方案在我的情况下不起作用。

我的理解是,FlatList 仅列出列表中的几个下一个项目 (initialNumToRender),并且只能滚动到这些项目,但不能滚动到其他项目。

如果列表项都具有相同的高度,我还有另一种解决方案,即使在长列表上也可以使用。那就是滚动到特定坐标:

export default MyComponent = props => {
  const flatListRef = useRef()

  return (
    <FlatList
      ref={flatListRef}
      ...
      onScrollToIndexFailed={({
        index,
        averageItemLength,
      }) => {
        // Layout doesn't know the exact location of the requested element.
        // Falling back to calculating the destination manually
        flatListRef.current?.scrollToOffset({
          offset: index * averageItemLength,
          animated: true,
        });
      }}
    />
  );
};