React Native使用FlexBox布局

我们在React Native中使用flexbox规则来指定某个组件的子元素的布局。Flexbox可以在不同屏幕尺寸上提供一致的布局结构。
React Native中的Flexbox的工作原理和web上的CSS基本一致,当然也存在少许差异。首先是默认值不同:flexDirection的默认值是column而不是row,而flex也只能指定一个数字值。

FLex Dirction

在组件的style中指定flexDirection可以决定布局的主轴。子元素是应该沿着水平轴(row)方向排列,还是沿着竖直轴(column)方向排列呢?默认值是竖直轴(column)方向。

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

export default class FlexDirctionBasics extends Component {
  render(){
    return(
        <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>
    );
  }
}

result


flexDirection:'row'

flexDirection:'column'

Justify Content

在组件的style中指定justifyContent可以决定其子元素沿着主轴的排列方式。子元素是应该靠近主轴的起始端还是末尾段分布呢?亦或应该均匀分布?对应的这些可选项有:flex-start、center、flex-end、space-around以及space-between。

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

export default class FlexDirctionBasics extends Component {
  render(){
    return(
        <View style={{flex:1,
        flexDirection:'column',
        justifyContent:'space-around'
        }}>
          <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>
    );
  }
}

result

justifyContent:'space-around'

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


Align Items

在组件的style中指定alignItems可以决定其子元素沿着次轴(与主轴垂直的轴,比如若主轴方向为row,则次轴方向为column)的排列方式。子元素是应该靠近次轴的起始端还是末尾段分布呢?亦或应该均匀分布?对应的这些可选项有:flex-start、center、flex-end以及stretch。


export default class FlexDirctionBasics extends Component {
  render(){
    return(
        <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>
    );
  }
}

result


flexDirection:'column', justifyContent:'center',alignItems:'center'

对于布局有影响的完整样式列表记录(http://reactnative.cn/docs/0.50/layout-props.html)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,865评论 1 92
  • H5移动端知识点总结 阅读目录 移动开发基本知识点 calc基本用法 box-sizing的理解及使用 理解dis...
    Mx勇阅读 4,703评论 0 26
  • 前言 学习本系列内容需要具备一定 HTML 开发基础,没有基础的朋友可以先转至 HTML快速入门(一) 学习 本人...
    珍此良辰阅读 4,579评论 2 19
  • 本文出自《React Native学习笔记》系列文章。 一款好的APP离不了一个漂亮的布局,本文章将向大家分享Re...
    CrazyCodeBoy阅读 37,547评论 3 278
  • 在React-Native中使用flexbox规则来指定某个组件的子元素的布局。Flexbox可以在不同屏幕尺寸上...
    Coder_Answer阅读 1,565评论 1 2