There may be a better way to achieve this with flexbox, but I usually define "percentage" helpers vw
and vh
for viewport width and viewport height, named after the CSS viewport size units of measurement:
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);
}
To flow items in a grid, you can then calculate an appropriate size for items, accounting for margins and viewport size:
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>
)
You should only use this technique if you have a known and limited number of items - for arbitrary amount of cards, you should use ListView
for performance reasons, and split your data set to rows manually.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…