react native 學習筆記----使用Flexbox佈局

Flexbox可以在不同屏幕尺寸上提供一致的佈局結構

一般來說,使用flexDirection、alignItems和 justifyContent三個樣式屬性就已經能滿足大多數佈局需求。

flexDirection 

在組件的style中指定flexDirection可以決定佈局的主軸。如果要指定子元素沿着水平軸方向排列,則指定爲row,沿着豎直軸方向排列指定爲column。默認值是豎直軸(column)方向。


Justify Content

在組件的style中指定justifyContent可以決定其子元素沿着主軸的排列方式。對應的這些可選項有:flex-start、center、flex-end、space-around以及space-between。

Align Items

在組件的style中指定alignItems可以決定其子元素沿着次軸(與主軸垂直的軸,比如若主軸方向爲row,則次軸方向爲column)的排列方式。對應的這些可選項有:flex-start、center、flex-end以及stretch。

佈局的簡單例子可以參看react native中文網:使用Flexbox佈局

或者官方網站:Layout with Flexbox

這節的內容加上前面的內容,我們就可以做出稍微複雜的界面了。

下面給出一個稍微複雜一點的佈局例子:

效果圖:


代碼如下:


import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';


class flexBoxTest extends Component {
  render() {
    return (
      // Try setting `justifyContent` to `center`.
      // Try setting `flexDirection` to `row`.
      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-between',
      }}>
        <View style={{alignItems:'stretch',justifyContent: 'center', height: 80, backgroundColor: 'darksalmon'}} >


        </View>


        <View style={{flexDirection:'row', height: 100,backgroundColor: 'skyblue'}} >
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center', backgroundColor: '#7fff00'}} >


          </View>
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center',backgroundColor: 'blue'}} >


          </View>
          <View style={{flex: 2,alignItems:'stretch',justifyContent: 'center', backgroundColor: '#00ffff'}} >


          </View>
        </View>


        <View style={{flex: 3,alignItems:'stretch', justifyContent: 'center',height: 50, backgroundColor: '#008b8b'}} >
          <Text style={ {fontSize:20,textAlign:'center'}}>Hello   andy!</Text>
        </View>


        <View style={{flex: 2,flexDirection:'row',alignItems:'stretch', height: 50, backgroundColor: '#fff8dc'}} >
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center', backgroundColor: '#7fff00'}} >


          </View>
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center',backgroundColor: '#dc143c'}} >


          </View>
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center', backgroundColor: '#00ffff'}} >


          </View>
        </View>


        <View style={{height: 60, alignItems:'stretch',backgroundColor: 'steelblue'}} >
        </View>
      </View>
    );
  }
}


AppRegistry.registerComponent('flexBoxTest', () => flexBoxTest);


參考文章:React Native佈局指南

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章