FlexBox
React-native采用FlexBox布局方案,是前端开发的一种布局方案。
主要有如下4个概念
- 弹性容器(flex Container):可以理解为父视图
- 弹性项目(flex item):可以认为是子视图
- 主轴(main axis):排列方向
- 侧轴交叉轴:与主轴交叉的的方向

理解图
弹性容器属性
我们可以通过调整弹性容器的属性来实现弹性容器的各种布局方式。主要的属性有如下4个
- flexDirection :控制主轴(main axis)的方向
- flexWrap :是否换行
- justifyContent : 子视图主轴(main axis)上的对齐方式
- alignItems :子视图在交叉轴(cross axis)上如何对齐
- alignSelf:item自己在交叉轴(cross axis)上的对齐方式,会覆盖默认的对齐方式
| 属性名 | 取值 |
|---|---|
| flexDirection |
row, row-reverse, column, column-reverse
|
| flexWrap |
wrap, nowrap,wrap-reverse
|
| justifyContent |
flex-start,flex-end, center, space-between, space-around,space-evenly
|
| alignItems |
flex-start, flex-end, center,stretch
|
| alignSelf |
auto, flex-start, flex-end, center, stretch
|
1. flexDirection
使用该属性控制主轴的方向:
- row :主轴为水平方向,起点在左端。
- row-reverse :主轴为水平方向,起点在右端。
- column(默认值) :主轴为垂直方向,起点在上沿。
- column-reverse :主轴为垂直方向,起点在下沿

flexDirection示例
2.flexWrap
该属性决定弹性项目是否换行
-
nowrap不换行(默认)
flexDirection:"row",
flexWrap:'nowrap'

nowrap
-
warp换行
flexDirection:"row",
flexWrap:"wrap"

image.png
3. justifyContent
使用该属性可以决定弹性项目主轴上的对齐方式
- flex-start(默认值):左对齐
- flex-end:右对齐
- center:居中
- space-between:两端对齐,项目之间的间隔都相等。
- space-around:每个项目两侧的间隔相等。所以,项目之间的间 隔比项目与边框的间隔大一倍。
*space-evenly:将每个元素的间隔相等
flexDirection:"row"示例

flexDirection:"row"
flexDirection:"column"示例
每个小图形的 marginTop为10

flexDirection:"column"
4. alignItems
该属性可以决定弹性项目在交叉轴上如何对齐
- flex-start:交叉轴的起点对齐。
- flex-end:交叉轴的终点对齐。
- center:交叉轴的中点对齐。
- baseline:项目的第一行文字的基线对齐。
- stretch(默认值):如果项目未设置高度或设为auto,将占满整个容器的高度。设置高度效果和flex-start一致

alignItems
4.1 alignItems.baseline
- 当
flexDirection:"column"时候
flexDirection:"column",
alignItems:"baseline"

baseline1
- 当
flexDirection:"row"时候
flexDirection:"row",
alignItems:"baseline"

baseline2
4. alignSelf
item自己在交叉轴上的对齐方式,会覆盖默认的对齐方式.flex-start和auto效果一样,stretch的效果与是否设置高度有关
<View style={{backgroundColor:"orange",width:414,height:500,flexDirection:"column"}}>
<Text style={{backgroundColor:"yellow",width:50,height:60,alignSelf:"flex-start"}}>1</Text>
<Text style={{backgroundColor:"red",width:50,height:80,alignSelf:"center"}}>2</Text>
<Text style={{backgroundColor:"#08f",height:80,alignSelf:"stretch"}}>3</Text>
<Text style={{backgroundColor:"#98f",width:100,height:80,alignSelf:"auto"}}>4</Text>
<Text style={{backgroundColor:"blue",width:50,height:100,alignSelf:"flex-end"}}>5</Text>
</View>

alignSelf效果图