react native 学习笔记----使用Flexbox布局

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

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

flexDirection 

在组件的style中指定flexDirection可以决定布局的主轴。如果要指定子元素沿着水平轴方向排列,则指定为row,沿着竖直轴方向排列指定为column。默认值是竖直轴(column)方向。


Justify Content

在组件的style中指定justifyContent可以决定其子元素沿着主轴的排列方式。对应的这些可选项有:flex-start、center、flex-end、space-around以及space-between。

Align Items

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

布局的简单例子可以参看react native中文网:使用Flexbox布局

或者官方网站:Layout with Flexbox

这节的内容加上前面的内容,我们就可以做出稍微复杂的界面了。

下面给出一个稍微复杂一点的布局例子:

效果图:


代码如下:


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


class flexBoxTest extends Component {
  render() {
    return (
      // Try setting `justifyContent` to `center`.
      // Try setting `flexDirection` to `row`.
      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-between',
      }}>
        <View style={{alignItems:'stretch',justifyContent: 'center', height: 80, backgroundColor: 'darksalmon'}} >


        </View>


        <View style={{flexDirection:'row', height: 100,backgroundColor: 'skyblue'}} >
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center', backgroundColor: '#7fff00'}} >


          </View>
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center',backgroundColor: 'blue'}} >


          </View>
          <View style={{flex: 2,alignItems:'stretch',justifyContent: 'center', backgroundColor: '#00ffff'}} >


          </View>
        </View>


        <View style={{flex: 3,alignItems:'stretch', justifyContent: 'center',height: 50, backgroundColor: '#008b8b'}} >
          <Text style={ {fontSize:20,textAlign:'center'}}>Hello   andy!</Text>
        </View>


        <View style={{flex: 2,flexDirection:'row',alignItems:'stretch', height: 50, backgroundColor: '#fff8dc'}} >
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center', backgroundColor: '#7fff00'}} >


          </View>
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center',backgroundColor: '#dc143c'}} >


          </View>
          <View style={{flex: 1,alignItems:'stretch',justifyContent: 'center', backgroundColor: '#00ffff'}} >


          </View>
        </View>


        <View style={{height: 60, alignItems:'stretch',backgroundColor: 'steelblue'}} >
        </View>
      </View>
    );
  }
}


AppRegistry.registerComponent('flexBoxTest', () => flexBoxTest);


参考文章:React Native布局指南

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章