在过去几周使用iOS本地反应之后,我似乎遇到了一些flex样式的缺点......特别是在涉及“响应”行为时。
例如,假设您要创建一个包含卡片的视图(这些卡片的元数据来自API)。您希望卡片的视图宽度的50%减去边距和填充,并在每个2之后换行。
我对此视图的当前实现将返回的数组拆分为包含2个项的行。列表容器有flex: 1, flexDirection: 'column
,行有flex: 1
,然后每张卡都有flex: 1
。最终结果是每行有2列,均匀占据视图宽度的一半。
似乎在React Native样式中没有简单的方法可以做到这一点,而不使用javascript对数据进行某种预处理,以便正确地进行样式设置。有没有人有什么建议?
React Native已经has percentage support:
<View style={[style.parent]}>
<View style={[style.child, {backgroundColor: '#996666'} ]} />
<View style={[style.child, {backgroundColor: '#339966'} ]} />
<View style={[style.child, {backgroundColor: '#996633'} ]} />
<View style={[style.child, {backgroundColor: '#669933'} ]} />
</View>
var style = StyleSheet.create({
parent: {
width: '100%',
flexDirection: 'row',
flexWrap: 'wrap'
},
child: {
width: '48%',
margin: '1%',
aspectRatio: 1,
}
})
使用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
,并手动将数据集拆分为行。
你可以使用justifyContent:'space-between'
<View style={styles.feed}>
<View style={styles.card} />
<View style={styles.card} />
<View style={styles.card} />
<View style={styles.card} />
</View>
feed: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
padding: 16,
justifyContent: 'space-between' }
card: {
backgroundColor: 'white',
width: '48%',
aspectRatio: 1,
marginBottom: 16 }