RN入门基础6:使用Flexbox布局

一、介绍

flexbox可以指定某个组件的子元素的布局。

Flexbox可以在不同屏幕尺寸上提供一致的布局结构。

一般来说,使用flexDirectionjustifyContent和 alignItems三个样式属性就已经能满足大多数布局需求。

注意:React Native中的Flexbox的工作原理和web上的CSS基本一致,当然也存在少许差异。首先是默认值不同:flexDirection的默认值是column而不是row,而flex也只能指定一个数字值。

1.Flex Direction(决定布局的主轴

在组件的style中指定flexDirection可以决定布局的主轴

设置子元素是沿着水平轴(row)方向排列,或者沿着竖直轴(column)方向排列。

默认值是竖直轴(column)方向。

2.Justify Content(子元素沿着主轴排列方式

在组件的style中指定justifyContent可以决定其子元素沿着主轴排列方式

扫描二维码关注公众号,回复: 2660270 查看本文章

子元素是应该靠近主轴的起始端还是末尾段分布呢?亦或应该均匀分布?

对应的这些可选项有:flex-startcenterflex-endspace-around以及space-between

3.Align Items(子元素沿着次轴排列方式。)

在组件的style中指定alignItems可以决定其子元素沿着次轴排列方式

次轴:(与主轴垂直的轴,比如若主轴方向为row,则次轴方向为column

子元素是应该靠近次轴的起始端还是末尾段分布呢?亦或应该均匀分布?

对应的这些可选项有:flex-startcenterflex-end以及stretch

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

以下面的代码为例:只有将子元素样式中的width: 50去掉之后,alignItems: 'stretch'才能生效。

额外图解:

简易布局图解

二、代码举例

Flex Direction(决定布局的主轴

Justify Content(子元素沿着主轴排列方式

Align Items(子元素沿着次轴排列方式。)

为了简单,我将三种常用布局方式写在一个类里

export default class myprojectname extends Component {
    render() {
        return (
            <View style={ {flex:1} }>

                {/*flexDirection 主轴*/}
                <View style={ {height:100,flexDirection: 'row'}}>
                    <View style={{flex: 1, backgroundColor: 'powderblue'}} />
                    <View style={{flex: 2, backgroundColor: 'skyblue'}} />
                    <View style={{flex: 3, backgroundColor: 'steelblue'}} />
                </View>

                <View style={ {height:50}}/>

                {/*justifyContent 主轴子部件排序方式*/}
                <View style={ {height:50,flexDirection: 'row',justifyContent: 'space-between',}}>
                    <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
                    <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
                    <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
                </View>

                <View style={ {height:50}}/>

                {/*justifyContent 次轴子部件排序方式*/}
                <View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center',}}>
                    <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
                    <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
                    <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
                </View>
            </View>
        );
    }
};

效果:

从上到下,依次是Flex Direction,Justify Content,Align Items

猜你喜欢

转载自blog.csdn.net/jinmie0193/article/details/81321313
今日推荐