RN之使用Flexbox布局

2019-10-11  本文已影响0人  一只西西狸

我们在React Native中使用flexbox规则来指定某个组件的子元素的布局。Flexbox可以在不同屏幕尺寸上提供一致的布局结构。
一般来说,使用flexDirectionalignItemsjustifyContent三个样式属性就已经能满足大多数布局要求。

这里有一份简易布局图解,可以给你一个大概的印象

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

Flex Direction

在组件的style中指定flexDirection可以决定布局的主轴。子元素默认沿着竖直轴(column)方向排列。

import React, { Component } from 'react';
import {  View } from 'react-native';
export default class FlexDirectionBasics extends Component {
  render() {
    return (
      // 尝试把`flexDirection`改为`column`看看
      <View style={{flex: 1, flexDirection: 'row'}}>
        <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>
    );
  }
};

运行结果如图


Layout Direction(布局方向)

布局方向指定层次结构中的子元素和文本的布局方向,布局方向也会影响边的开头和结尾。默认情况下,React Native会按照LTR布局方向布局,在这种模式下,起始指的是左边,结尾指的是右边。

Justify Content

在组件的style中指定justifyContent可以决定其子元素沿着主轴的排列方式。子元素的分布选项有:flex-startcenterflex-endspace-aroundspace-between以及space-evenly

import React, { Component } from 'react';
import {  View } from 'react-native';
export default class JustifyContentBasics extends Component{
    render(){
        return(
        <View style={{
            flex:1,
            flexDirection:'column',
            JustifyContent:'space-between',
        }}>
        <View style={{width:50,height:50,backgroundColor:'powerblue'}} />
        <View style={{width:50,height:50,backgroundColor:'skyblue'}} />
        <View style={{width:50,height:50,backgroundColor:'steelblue'}} />
        </View>
        );
    }
};

运行结果如图


Align Items

在组件的style中指定alignItems可以决定其子元素沿着次轴(与主轴垂直的轴,比如若主轴方向为row,则次轴方向为column)的排列方式。子元素的分布选项有:flex-startcenterflex-end以及stretch

注意:要使用`stretch`选项生效的话,子元素在次轴方向上不能有固定的尺寸。
以下面的代码为例:只有将子元素样式中的`width:50`去掉之后,`alignItems:'stretch'`才能生效。
import React, { Component } from 'react';
import {  View } from 'react-native';
export default class AlignItemsBasics extends Component{
    render(){
        return(
        <View style={{
            flex:1,
            flexDirection:'column',
            JustifyContent:'center',
            alignItems:'stretch',
        }}>
        <View style={{width:50,height:50,backgroundColor:'powerblue'}}/>
        <View style={{height:50,backgroundColor:'skyblue'}}/>
        <View style={{height:100,backgroundColor:'steelblue'}}/>
        </View>
        );
    }
};

运行结果如下


深入学习

以上介绍了一些基础知识,但要运用好布局,我们还需要其他很多的样式。对于布局有影响的完整样式列表记录在这个文档中

在进行真正的开发工作之前,还应记住一个常用的知识点:如何使用TextInput组件来处理用户输入

上一篇 下一篇

猜你喜欢

热点阅读