前言
之前我们讲了很多React-native的基础控件,为了方便大家的理解,我们来对react-native的布局做一个总结,观看本节知识,你将看到。
- 宽度单位和像素密度
- flex的布局
- 图片布局
- 绝对定位和相对定位
- padding和margin的区别和应用场合
- 文本元素
宽度单位和像素密度
我们知道在Android中是用设备像素来作为单位的(后面又出现了百分比这么 一个概念),iOS中后面也有了Auto Layout和1倍图,二倍图等概念(xib+storyboard)。然而react的宽度不支持百分比,那么React怎么提供尺寸的呢?PixelRatio,PixelRatio及像素密度,可以看看官方的介绍。
var image = getImage({
width: 200 * PixelRatio.get(),
height: 100 * PixelRatio.get()
});
<Image source={image} style={
{
width: 200, height: 100}} />
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
flex的布局
我们知道一个div如果不设置宽度,默认的会占用100%的宽度, 为了验证100%这个问题, 做三个实验:
- 根节点上方一个View, 不设置宽度
- 固定宽度的元素上设置一个View, 不设置宽度
- flex的元素上放一个View宽度, 不设置宽度
<Text style={[styles.text, styles.header]}>
根节点上放一个元素,不设置宽度
</Text>
<View style={
{
height: 20, backgroundColor: '#333333'}} />
<Text style={[styles.text, styles.header]}>
固定宽度的元素上放一个View,不设置宽度
</Text>
<View style={
{
width: 100}}>
<View style={
{
height: 20, backgroundColor: '#333333'}} />
</View>
<Text style={[styles.text, styles.header]}>
flex的元素上放一个View,不设置宽度
</Text>
<View style={
{
flexDirection: 'row'}}>
<View style={
{
flex: 1}}>
<View style={
{
height: 20, backgroundColor: '#333333'}} />
</View>
<View style={
{
flex: 1}}/>
</View>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
来看一下运行的结果:
水平垂直居中
css 里边经常会将一个文本或者图片水平垂直居中,如果使用过css 的flexbox当然知道使用alignItems 和 justifyContent ,那如果用React Native如何实现呢?
<Text style={[styles.text, styles.header]}>
水平居中
</Text>
<View style={
{
height: 100, backgroundColor: '#333333', alignItems: 'center'}}