react的宽度不支持百分比,设置宽度时不需要带单位 {width: 10}
, 那么10代表的具体宽度是多少呢?
不知道是官网文档不全还是我眼瞎,反正是没找到,那做一个实验自己找吧:
var Dimensions = require('Dimensions'); <Text style={styles.welcome}> window.width={Dimensions.get('window').width + '\n'} window.height={Dimensions.get('window').height + '\n'} pxielRatio={PixelRatio.get()} </Text>
默认用的是iphone6的模拟器结果是:
window.width=375 window.height=667 pxielRatio=2
我们知道iphone系列的尺寸如下图:
可以看到iphone 6的宽度为 375pt,对应了上边的375,由此可见react的单位为pt。 那如何获取实际的像素尺寸呢? 这对图片的高清化很重要,如果我的图片大小为100*100 px. 设置宽度为100 * 100. 那在iphone上的尺寸就是模糊的。 这个时候需要的图像大小应该是 100 * pixelRatio的大小 。
react 提供了PixelRatio 的获取方式https://facebook.github.io/react-native/docs/pixelratio.html
var image = getImage({ width: 200 * PixelRatio.get(), height: 100 * PixelRatio.get() }); <Image source={image} style={ {width: 200, height: 100}} />
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>
结果可以看到flex的元素如果不设置宽度, 都会百分之百的占满父容器。
水平垂直居中
css 里边经常会做的事情是去讲一个文本或者图片水平垂直居中,如果使用过css 的flexbox当然知道使用alignItems
和 justifyContent
. 那用react-native也来做一下实验
<Text style={[styles.text, styles.header]}> 水平居中 </Text> <View style={ {height: 100, backgroundColor: '#333333', alignItems: 'center'}}> <View style={ {backgroundColor: '#fefefe', width: 30, height: 30, borderRadius: 15}}/> </View> <Text style={[styles.text, styles.header]}> 垂直居中 </Text> <View style={ {height: 100, backgroundColor: '#333333', justifyContent: 'center'}}> <View style={ {backgroundColor: '#fefefe', width: 30, height: 30, borderRadius: 15}}/> </View> <Text style={[styles.text, styles.header]}> 水平垂直居中 </Text> <View style={ {height: 100, backgroundColor: '#333333', alignItems: 'center', justifyContent: 'center'}}> <View style={ {backgroundColor: '#fefefe', width: 30, height: 30, borderRadius: 15}}/> </View>
网格布局
网格布局实验, 网格布局能够满足绝大多数的日常开发需求,所以只要满足网格布局的spec,那么就可以证明react的flex布局能够满足正常开发需求
等分的网格
<View style={styles.flexContainer}> <View style={styles.cell}> <Text style={styles.welcome}> cel