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越大,所佔父佈局的空間越大

相關文章
相關標籤/搜索