chenbin92 / React-native-example

Learning react native
61 stars 16 forks source link

React Naitve之 Flexbox 布局 #9

Open chenbin92 opened 8 years ago

chenbin92 commented 8 years ago

Flexbox 是 React Native 应用开发中必不可少的一部分,也是最常用最基础的内容,下面让我们一起去探索一下什么是flexbox布局:

Flexbox 布局是什么?

Flex 是 Flexible Box 的缩写,意为"弹性盒子布局",是 CSS3 新增加的一个布局模块;做过 web 前端开发的人员都清楚,传统的页面布局基于盒状模型,依赖 display属性 + position属性 + float属性。相反的,flexbox 提供了更加灵活的特性,可以简便、完整、响应式地实现各种页面布局。

布局模型

flexbox布局由伸缩容器伸缩项目组成。任何一个元素都可以指定为 flexbox 布局,其中设为 display: flexdisplay: inline-flex 的元素称为伸缩容器;

换句通俗的话讲就是:只有设置为 display: flexdisplay: inline-fiex 的元素才能叫做伸缩容器,它的子元素才能使用伸缩布局模型提供的属性来排版。

UI 组件

在讲解伸缩容器属性之前,我们需要先简单了解一下 React Native 提供的基础UI组件,在下面我们会用到这些UI组件结合 flexbox 去布局。

就像学习 HTML 一样,标签十分重要。开发web应用程序时,需要使用很多的 HTML 标签,例如 h1~h6pulli等等;但在 React Native中,只提供了基础的UI 组件:

ReactNativeUiComponent

在 React Native 中使用 flexbox

React Native 将 web 中的flexbox 布局引入进来,使得视图的布局更加简单;目前 React Native 主要支持的 flexbox 属性如下:

flex: number

flex

flexDirection

flexDirection:row | column

flexDirection

flexWrap

flexWrap:wrap | nowrap

flexWrap

alignItems

alignItems:flex-start | flex-end | center | stretch

alignItems

justifyContent

justifyContent:flex-start | flex-end | center | space-between | space-around

justifyContent

alignSelf

alignSelf:auto | flex-start | flex-end | center | stretch

alignSelf:auto

下面通过实例演示来实践flexbox布局:

测试一:测试ViewText组件的默认宽度

<View>
   <Text style={{backgroundColor: 'red',height: 100}}> Text 组件默认占据100%的宽度</Text>
   <Text style={{backgroundColor: '#469EDD',height: 100}}> Text 组件默认是纵向布局</Text>
</View>

flexboxExample1

结论: Text 组件默认占据100%的宽度,默认是纵向布局

测试二:测试flex属性

<View style={{marginTop: 22,flex: 1,flexDirection: 'row', justifyContent: 'flex-start'}}>
    <Text style={{backgroundColor: 'red',height: 100}}>1. 父元素必须设置flex属性,才能使用flexbox布局</Text>
    <Text style={{backgroundColor: '#469EDD',height: 100}}> 2. flexDirection默认为纵向布局,即主轴默认是竖直方向</Text>
</View>

flexboxExample2

结论:

待补充...