FlatList设为horizontal:true时子项百分比宽度失效问题咨询
解决React Native横向FlatList百分比宽度失效的问题
嘿,这个问题我之前开发时也踩过坑!其实根源在于横向FlatList的布局逻辑和纵向不一样:
当你把horizontal={true}开启后,FlatList的滚动容器(内部的ScrollView)宽度不再默认撑满父容器,而是会自适应子项的宽度。这时候你给子项设置width: '100%',它的参考对象是滚动容器的宽度——而滚动容器的宽度又由子项宽度决定,相当于陷入了循环,自然达不到“占满屏幕宽度”的预期效果。而纵向模式下,FlatList的容器宽度默认是父容器的100%,所以百分比宽度能正常生效。
下面给你两种靠谱的解决方案:
方案1:类组件用Dimensions获取屏幕宽度
先导入Dimensions,直接获取当前窗口的宽度,然后给子项设置这个固定值:
import React from 'react'; import { View, Text, FlatList, Dimensions, StyleSheet } from 'react-native'; const screenWidth = Dimensions.get('window').width; class App extends React.Component { _renderItem = ({ item }) => { return ( <View style={{ width: screenWidth, height: 100, backgroundColor: '#eee', marginVertical: 5 }}> <Text>{item.key}</Text> </View> ); }; render() { return ( <View style={styles.container}> <FlatList data={[{ key: 1 }, { key: 2 }, { key: 3 }]} renderItem={this._renderItem} horizontal={true} showsHorizontalScrollIndicator={false} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 50, }, }); export default App;
⚠️ 注意:Dimensions.get('window')只会在组件初始化时获取一次宽度,如果你的App需要支持屏幕旋转,得额外监听尺寸变化事件来更新宽度值。
方案2:函数组件用useWindowDimensions(推荐)
如果你是用函数组件开发,React Native提供的useWindowDimensions Hook会自动监听窗口尺寸变化,比Dimensions更省心:
import React from 'react'; import { View, Text, FlatList, useWindowDimensions, StyleSheet } from 'react-native'; function App() { const { width: screenWidth } = useWindowDimensions(); const _renderItem = ({ item }) => { return ( <View style={{ width: screenWidth, height: 100, backgroundColor: '#eee', marginVertical: 5 }}> <Text>{item.key}</Text> </View> ); }; return ( <View style={styles.container}> <FlatList data={[{ key: 1 }, { key: 2 }, { key: 3 }]} renderItem={_renderItem} horizontal={true} showsHorizontalScrollIndicator={false} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 50, }, }); export default App;
这两种方法都能让横向FlatList的子项准确占满屏幕宽度,完美解决你的问题~
内容的提问来源于stack exchange,提问作者Kakar
相关产品推荐
相关产品推荐

