Flexbox主要用flexDirection、alignItems和 justifyContent這三種布局
flexDirection
相當于Android中的orientation
flexDirection可以決定布局的主軸。子元素是應該沿著水平軸(row)方向排列,還是沿著豎直軸(column)方向排列呢?默認值是豎直軸(column)方向
flexDirection(RN) | orientation(Android) |
---|---|
row | horizontal |
column | vertical |
Justify Content
相當于Android中的layout_gravity
對應的這些可選項有:flex-start、center、flex-end、space-around以及space-between
RN | Android |
---|---|
flex-start | left |
flex-start | right |
center | center |
space-between | - |
space-around | - |
space-between:占用真個屏幕,空余部分留到中間
<View style={{flex: 1, flexDirection: 'row',justifyContent: 'space-between',}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
<View style={{width: 50, height: 50, backgroundColor: '#ffffff'}} />
</View>
圖片.png
space-around:占用整個屏幕,平均分配
<View style={{flex: 1, flexDirection: 'row',justifyContent: ’space-around',}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
<View style={{width: 50, height: 50, backgroundColor: '#ffffff'}} />
</View>
圖片.png
Align Items
alignItems可以決定其子元素沿著次軸(與主軸垂直的軸,比如若主軸方向為row,則次軸方向為column)的排列方式。子元素是應該靠近次軸的起始端還是末尾段分布呢?亦或應該均勻分布?對應的這些可選項有:flex-start、center、flex-end以及stretch。
flex-start、center、flex-end不做介紹,主要介紹下stretch
注意:要使stretch選項生效的話,子元素在次軸方向上不能有固定的尺寸。以下面的代碼為例:只有將子元素樣式中的height: 50去掉之后,alignItems: 'stretch'才能生效。
<View style={{flex: 1, flexDirection: 'row',justifyContent: 'space-around',alignItems:'stretch'}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50,height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50,height: 50, backgroundColor: 'steelblue'}} />
<View style={{width: 50, backgroundColor: '#ffffff'}} />
</View>
效果圖
圖片.png