React Native入门 认识Flexbox布局

Flexbox布局是由W3C在09年提出的在Web端取代CSS盒子模型的一种布局方式。布局

ReactNative实现了Flexbox布局的大部分功能。flex

 

Flexbox布局所使用的属性,基本能够分为两大类:spa

  1. 决定子组件排列规则的属性,例如:flexDirection , flexWrap, justifyContent, alignItems等。
  2. 决定自身的显示规则的属性,例如:alignSelf, flex等

 

[1] flexDirection3d

    设置子组件的排列顺序,默认column(纵向排列),其余row(横向排列)code

代码:blog

type Props = {}; export default class App extends Component<Props> { render() { return ( <View style={styles.container}>
          <View style={styles.view1}></View>
          <View style={styles.view2}></View>
      </View>
 ); } } const styles = StyleSheet.create({ container: { flex: 1, //justifyContent: 'center',
    //alignItems: 'center',
    flexDirection: 'row', //这里显式声明为row,将横向排列,不然默认纵向排列 backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, view1: { height: 150, width: 150, backgroundColor: 'red' }, view2: { height: 150, width: 150, backgroundColor: 'green' } });

如图:io

 

[2]flexWrap class

  设置是否换行,默认值nowrap(不换行),其余wrap容器

 

当咱们将两个子View的宽换为200时,绿框将溢出屏幕,而只显示一半bfc

 view1: { height: 200, width: 200, backgroundColor: 'red' }, view2: { height: 200, width: 200, backgroundColor: 'green'

如图:

 

将container样式改成wrap, 溢出的绿框将会另起一行。

 

 

[3] justifyContent

    justifyContent 属性表示该组件的子组件横向排列的其父容器的哪一个位置。

    取值有:flex-start, flex-end, center, space-between, space-around

   

 container: { flex: 1, //justifyContent: 'center',
    //alignItems: 'center',
    flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-around', //修改的这一行 backgroundColor: '#F5FCFF', },

flex-start:贴左

flex-end:  贴右

center:   子组件群横向居中

space-between:空白在子组件中间

space-around:空白在子组件周围(每一个子组件的两边)

 

[4] alignItems

  属性表示该组件的子组件纵向排列的其父容器的哪一个位置。  

   取值:flex-start, flex-end, center, baseline, stretch

center子组件群父容器的纵向向居中

flex-start:贴父容器顶

flex-end: 贴父容器底

baseline:现象与flex-start一致(待补)

stretch: 现象与flex-start一致(待补)

 

[5] alignSelf

  代表某个特定组件的排列状况

  取值:flex-start, flex-end, center, stretch

center: 当前组件基于父组件的布局后进行居中(父布局时横向排列,则纵向居中;横向排列,则纵向居中)

flex-start:当前组件基于父组件的布局后进行贴左(同上)

flex-end:当前组件基于父组件的布局后进行贴右(同上)

[6] flex

  flex属性能够让组件动态的去计算和配置本身所占用的空间大小,取值是数值

代码:

 container: { flex: 1, //这个父布局的flex必需要,它表明的是它在其父布局的比重,没有将是一片空白 backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, view1: { flex: 1, backgroundColor: 'red' }, view2: { flex: 1, backgroundColor: 'green' }

结果:

 

能够看出flex,相似与Android 的weight(比重),将父布局的子布局的flex元素取出对比来计算出其实际大小。

当将绿色组件的flex属性改成2时,绿组件占父布局的三分之二,可见flex越大,所占父布局的空间越大

相关文章
相关标签/搜索