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