React Native FlatList无法水平滚动 无法滑动到第二、第三列表项
问题原因
- 你给FlatList的
contentContainerStyle配置了flex: 1,这个属性会强制FlatList的滚动内容容器尺寸和FlatList本身的可视区域尺寸完全一致,内容不会超出可视区域,自然无法产生滚动效果。 - 每个列表项的宽度设置为
"100%",这个百分比是相对于滚动内容容器的宽度,而不是可视区域宽度。水平滚动场景下滚动容器宽度本应为所有子项宽度之和,按你现有写法会导致每个子项宽度异常,不符合分页滚动占满全屏的预期。
修复步骤
- 移除FlatList配置中的
contentContainerStyle={{ flex: 1}}属性 - 把列表项的宽度改为FlatList可视区域的宽度,可以用React Native提供的
useWindowDimensions钩子快速获取屏幕宽度,适配你的分页滚动需求
修复后代码示例
import { useWindowDimensions } from 'react-native'; export const Flat: React.FC = () => { // 获取屏幕宽度,作为每个分页的宽度 const { width: screenWidth } = useWindowDimensions(); const aaa = [{}, {}, {}] const renderItem = ({item, index}: any) => { if(index === 0){ return <View style={{width: screenWidth, backgroundColor: "green"}}> <Text> asdasad </Text> </View> } else if(index === 1){ return <View style={{width: screenWidth, backgroundColor: "red"}}> <Text> asdasad </Text> </View> } return <View style={{width: screenWidth, backgroundColor: "blue"}}> <Text> asdasad </Text> </View> } return <View style={{flex: 1}}> <FlatList style={{flex: 1}} horizontal={true} data={aaa} renderItem={renderItem} keyExtractor={(item, index) => index.toString()} pagingEnabled={true} /> </View> }
如果你的FlatList不需要占满全屏,可以给外层容器绑定onLayout回调获取实际宽度,再赋值给列表项即可。
内容的提问来源于stack exchange,提问作者tokenaizer
相关产品推荐
相关产品推荐

