如何消除React Native横向FlatList列表项间的间隙?
React Native 横向FlatList列表项间隙问题解决方法
在React Native 0.72.7版本中,当横向FlatList与一个宽度≤50的View处于flexDirection: 'row'的容器内时,若FlatList的列表项宽度≤59,列表项之间会出现细小间隙(表现为红色列表项之间的白色空隙)。问题复现代码如下:
import React from 'react'; import {FlatList, View} from 'react-native'; const App = () => { return ( <View style={{flexDirection: 'row'}}> <View style={{height: 500, width: 50, backgroundColor: 'blue'}} /> <FlatList horizontal data={[1, 2, 3, 4, 5]} renderItem={() => ( <View style={{height: 100, width: 50, backgroundColor: 'red'}} /> )} /> </View> ); }; export default App;
解决方法
以下几种方案可消除该间隙,可根据实际场景选择:
关闭
removeClippedSubviews属性:该属性默认开启用于优化长列表性能,但在特定布局下会引发渲染间隙,关闭后即可修复:<FlatList horizontal removeClippedSubviews={false} // 其他原有属性 />为FlatList添加
flex: 1样式:确保FlatList在容器内占据正确的可用空间,避免布局计算偏差:<FlatList horizontal style={{flex: 1}} // 其他原有属性 />为列表项设置
overflow: 'hidden':强制列表项边界严格按设置宽度渲染,规避像素对齐问题:renderItem={() => ( <View style={{height: 100, width: 50, backgroundColor: 'red', overflow: 'hidden'}} /> )}
修改后的完整示例代码
import React from 'react'; import {FlatList, View} from 'react-native'; const App = () => { return ( <View style={{flexDirection: 'row'}}> <View style={{height: 500, width: 50, backgroundColor: 'blue'}} /> <FlatList horizontal removeClippedSubviews={false} style={{flex: 1}} data={[1, 2, 3, 4, 5]} renderItem={() => ( <View style={{height: 100, width: 50, backgroundColor: 'red', overflow: 'hidden'}} /> )} /> </View> ); }; export default App;
内容的提问来源于stack exchange,提问作者kabakaba
相关产品推荐
相关产品推荐

