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',backgroundColor: '#7fff00'}} >


</View>
<View style={{flex: 1,backgroundColor: 'blue'}} >


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


</View>
</View>


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


<View style={{flex: 2,flexDirection:'row',backgroundColor: '#fff8dc'}} >
<View style={{flex: 1,backgroundColor: '#dc143c'}} >


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


</View>
</View>


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


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


参考文章React Native布局指南

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...