React Native之Flexbox

2018-09-04  本文已影响12人  谢尔顿

1. flexDirection

flexDirection决定布局的主轴,值为row时,子元素沿着水平方向排列,值为column时,子元素沿着竖直轴方向排列。
示例代码如下:

import React, {Component} from 'react'

import {
    StyleSheet,
    View,
} from 'react-native'

export default class LotsOfStyles extends Component<Props> {
    static navigationOptions = {
        // title: 'page 1',
        title: 'Flexbox布局',
    };

    render() {
        return (
            <View style={{flex:1,flexDirection: 'row'}}>
                <View style={{width: 100,height:100,backgroundColor:'powderblue'}}/>
                <View style={{width: 100,height:100,backgroundColor:'skyblue'}}/>
                <View style={{width: 100,height:100,backgroundColor:'steelblue'}}/>
            </View>
        );
    }
}

效果如下:


当flexDirection为cloumn时,效果如下:


flexDirection为cloumn

2. justifyContent

在style中justifyContent可以决定其子元素沿着主轴的排列方式。对应的值可以有flex-start、center、flex-end、space-around、space-between以及space-evenly。

import React, {Component} from 'react'

import {
    StyleSheet,
    View,
} from 'react-native'

export default class LotsOfStyles extends Component<Props> {
    static navigationOptions = {
        // title: 'page 1',
        title: 'Flexbox布局',
    };

    render() {
        return (
            <View style={{flex:1,flexDirection: 'column',justifyContent: 'space-between'}}>
                <View style={{width: 100,height:100,backgroundColor:'powderblue'}}/>
                <View style={{width: 100,height:100,backgroundColor:'skyblue'}}/>
                <View style={{width: 100,height:100,backgroundColor:'steelblue'}}/>
            </View>
        );
    }
}

效果图:


space-between

3. alignItems

在style中指定alignItems可以决定其子元素沿着次轴(与主轴垂直的轴,比如若主轴为row,则次轴方向为column)的排列方式。对应的值可以有flex-start、center、flex-end、stretch。

import React, {Component} from 'react'

import {
    StyleSheet,
    View,
} from 'react-native'

export default class LotsOfStyles extends Component<Props> {
    static navigationOptions = {
        // title: 'page 1',
        title: 'Flexbox布局',
    };

    render() {
        return (
            <View style={{
                flex: 1,
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'stretch'
            }}>
                <View style={{width: 100, height: 100, backgroundColor: 'powderblue'}}/>
                <View style={{height: 50, backgroundColor: 'skyblue'}}/>
                <View style={{height: 100, backgroundColor: 'steelblue'}}/>
            </View>
        );
    }
}

注:stretch生效的话,子元素在次轴方向上不能有固定的尺寸。

stretch

关于这三个样式,还是需要我们多练习才能找到规律,多做一些组合的练习,就能完全掌握。

上一篇 下一篇

猜你喜欢

热点阅读