- 使用
flexbox
(因为它是react-native) - 父容器的宽度是百分比
- 元素数量可以是 4/5/6/7..
- 元素之间的间隙相同
- 如下图所示
这是我的代码:
const styles = {
container: {
width: screenWidth * 0.9,
flexWrap: 'wrap',
flexDirection: 'row'
},
item: {
backgroundColor: 'red',
height: 120,
width: (width * 0.9 - 20) / 3,
marginBottom: 10
}
}
<View style={styles.container}>
{items.map((item, idx) =>
<View style={[styles.item, { marginHorizontal: idx % 3 === 1 ? 10 : 0}]} />
)}
</View>
还有其他更好的方法来实现这种布局吗?
最佳答案
请查看这个演示: https://snack.expo.io/@immynk/demo
根据需要的高度宽度,您可以在 Flatlist 内的 View 组件中使用,也可以根据需要放置 numColumns
import * as React from 'react';
import { Text, View, StyleSheet, FlatList, Dimensions } from 'react-native';
import Constants from 'expo-constants';
const DATA = [
{
key: 1,
},
{
key: 2,
},
{
key: 3,
},
{
key: 4,
},
{
key: 5,
},
{
key: 6,
},
];
export default class App extends React.Component {
render() {
return (
<View>
<FlatList
showsVerticalScrollIndicator={false}
data={DATA}
numColumns={3}
renderItem={({ item, index }) => {
return (
<View
style={{
backgroundColor: "red",
paddingHorizontal: 5,
paddingVertical: 5,
flexDirection: "row",
height:130,
width:130
}}>
<View style={{backgroundColor:"white",width:"100%"}}>
</View>
</View>
);
}}
keyExtractor={item => item.key}
/>
</View>
);
}
}
关于css - 有没有更好的方法可以在柔性显示中的元素之间保持相同的间隙空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60387511/