如何让SectionList中嵌套的所有FlatList滚动到底部?
解决方案
问题原因
你猜的完全正确:单个useRef会被最后渲染的FlatList覆盖,导致只能获取到最后一个FlatList的引用。
具体修正步骤
- 改用数组存储多个FlatList的引用:用
useRef初始化一个空数组,用来保存所有FlatList的实例。 - 给每个FlatList绑定对应索引的ref:利用
renderSectionHeader提供的index参数,把每个FlatList的ref存入数组对应位置。 - 遍历ref数组调用滚动方法:点击按钮时,循环数组里的每个FlatList引用,逐个调用
scrollToEnd。
修正后的代码示例
... // 初始化数组存储所有FlatList的ref const flatListRefs = useRef([]); const scrollToEnd = () => { // 遍历每个ref,调用滚动方法 flatListRefs.current.forEach(ref => { if (ref) { // 确保ref存在再执行,避免报错 ref.scrollToEnd({ animating: true }); } }); }; ... <SectionList contentContainerStyle={styles.sectionListContainer} stickySectionHeadersEnabled={false} sections={myData} // 接收index参数,用来对应ref数组的位置 renderSectionHeader={({ section, index }) => ( <> <FlatList horizontal data={section.data} contentContainerStyle={styles.flatlistContainer} renderItem={({ item }) => ( <Button onPress={() => updateData(item.id)}> <ListItem item={item} /> </Button> )} showsHorizontalScrollIndicator={false} // 将当前FlatList实例存入数组对应索引 ref={el => flatListRefs.current[index] = el} /> </> )} renderItem={() => null} />
额外注意点
- 如果section数量后续会动态变化,不需要硬编码长度,保持
flatListRefs数组和sections数量同步即可。 - 每次组件渲染时,ref的赋值函数会重新执行,确保数组里的每个位置都对应最新的FlatList实例。
内容的提问来源于stack exchange,提问作者Aleksandar Zoric
相关产品推荐
相关产品推荐

