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

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

scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed

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

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

请您参考如下方法:

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

我通过使用initialScrollIndex在FlatList上设置选定的索引来解决这个问题。当 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 }); 
    }); 
  }} 
/> 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!