1. 程式人生 > >React Native學習(九)—— 使用Flexbox布局

React Native學習(九)—— 使用Flexbox布局

styles BE art 分享圖片 category urn def ger p s

本文基於React Native 0.52

Demo上傳到Git了,有需要可以看看,寫了新內容會上傳的。Git地址 https://github.com/gingerJY/React-Native-Demo

一、主軸方向 flexDirection

  flexDirection決定主軸的排列方向。

  1、column——豎直(默認)

 技術分享圖片 

2、row——水平

 技術分享圖片

二、主軸排列方式 justifyContent 

  justifyContent決定其子元素沿著主軸的排列方式。(以下例子主軸方向為row)

  1、flex-start——子元素靠近主軸起始端

    技術分享圖片

  2、flex-end——子元素靠近主軸末尾端

    技術分享圖片

  3、center——主軸居中

    技術分享圖片

  4、space-around 和 space-between 都是均勻分布,區別如下圖

    技術分享圖片  技術分享圖片

三、次軸排列方式 alignItems

  alignItems決定其子元素沿著次軸的排列方式。(以下例子主軸方向為row,次軸方向為column

  1、flex-start——子元素靠近次軸起始端

    技術分享圖片

2、flex-end——子元素靠近次軸末尾端

    技術分享圖片

3、center——子元素次軸居中

    技術分享圖片

4、stretch——子元素撐開、填滿次軸(子元素在次軸不能有固定尺寸)

    技術分享圖片

四、示例代碼

可以自己試著改變看看,需要註意的是alignItems設為stretch時,要把子元素的次軸尺寸去掉(例如主軸方向為row,則去掉height)。

import React, { Component } from ‘react‘;
import {
    StyleSheet,
    View,
    Text,
    Dimensions,
} from ‘react-native‘;

// 取得屏幕的寬高Dimensions
const { width, height } = Dimensions.get(‘window‘);

export default class category extends Component {

    render() {
        return (
            <View style={styles.container}> 
                <Text>category</Text>
                <View style={styles.flexBox}>  
                    <View style={{width: 80, height:80, backgroundColor: ‘powderblue‘}} />
                    <View style={{width: 80, height:80, backgroundColor: ‘skyblue‘}} />
                    <View style={{width: 80, height:80, backgroundColor: ‘steelblue‘}} /> 
                </View>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: ‘center‘,
    },
    flexBox:{
        width:width,
        height:280,
        borderWidth:1,

        flexDirection:‘row‘,//主軸方向 
        justifyContent:‘space-between‘, //flex-start,flex-end,center,space-between,space-around
        alignItems:‘center‘,//flex-start,flex-end,center,stretch
    }
});

  

END-------------------------------------------------------

  

React Native學習(九)—— 使用Flexbox布局