使用 flexbox 可能有更好的方法来实现这一点,但我通常定义“百分比”助手vw
以及vh
视口宽度和视口高度,以 CSS 视口大小测量单位命名:
import {Dimensions} from 'react-native';
function vw(percentageWidth) {
return Dimensions.get('window').width * (percentageWidth / 100);
}
function vh(percentageHeight) {
return Dimensions.get('window').height * (percentageHeight / 100);
}
要在网格中流动项目,您可以计算项目的适当大小,考虑边距和视口大小:
const COLUMNS = 3;
const MARGIN = vw(1);
const SPACING = (COLUMNS + 1) / COLUMNS * MARGIN;
const grid = {
flex: 1,
flexWrap: 'wrap',
flexDirection: 'row',
justifyContent: 'flex-start'
};
const cell = {
marginLeft: MARGIN,
marginTop: MARGIN,
width: vw(100) / COLUMNS - SPACING
}
return (
<View style={grid}>
{this.props.things.map(thing => <View style={cell} />)}
</View>
)
如果您的项目数量已知且数量有限,您应该只使用此技术 - 对于任意数量的卡片,您应该ListView
出于性能原因使用,并手动将数据集拆分为行。