说到布局,不论是Android还是iOS还是web前端,都有涉及到,React Native中也有布局,主要采用了类似css中的flexbox布局,不过这种布局跟css中的flexbox布局稍微有点不同,下面就记录在React Native中使用flexbox布局的方法,主要涉及到如下几个属性:
1、flex
2、flexDirection
3、alignSelf
4、alignItems
5、justifyContent
还有其他的一些属性,可以参考React Native中文文档:http://wiki.jikexueyuan.com/project/react-native/flexbox.html,或者css中有关flexbox属性的文档:http://www.runoob.com/cssref/css3-pr-align-items.html
下面就来一一解释上面几个属性:
class Test extends Component { render() { return ( <View style={styles.container}> <View style={styles.child1}> </View> <View style={styles.child2}> </View> <View style={styles.child3}> </View> </View> ); } } const styles = { container: { flex: 1, flexDirection: 'column', //子元素垂直排列,默认是垂直排列的 }, child1: { flex: 1, backgroundColor: '#aa0000', }, child2: { flex: 1, backgroundColor: '#aaaa00', }, child3: { flex: 2, backgroundColor: '#0000aa', } };在上面的代码中,分别为child1, child2, child3设置了flex属性为1, 1, 2,代表这三个元素在垂直方向上是按1:1:2的比例排列的,在手机上显示出来的效果如下图:
class Test extends Component { render() { return ( <View style={styles.container}> <Text style={[styles.block1, styles.text]}>alignSelf: 'flex-start'</Text> <Text style={[styles.block2, styles.text]}>alignSelf: 'flex-end'</Text> <Text style={[styles.block3, styles.text]}>alignSelf: 'center'</Text> <Text style={[styles.block4, styles.text]}>alignSelf: 'auto'</Text> <Text style={[styles.block5, styles.text]}>alignSelf: 'stretch'</Text> </View> ); } } const styles = { container: { flex: 1, }, text: { fontSize: 13, color: '#ff0000', marginTop: 10, }, block1: { width: 150, height: 40, backgroundColor: '#6699ff', alignSelf: 'flex-start', }, block2: { width: 150, height: 40, backgroundColor: '#6699ff', alignSelf: 'flex-end', }, block3: { width: 150, height: 40, backgroundColor: '#6699ff', alignSelf: 'center', }, block4: { width: 150, height: 40, backgroundColor: '#6699ff', alignSelf: 'auto', }, block5: { height: 40, backgroundColor: '#6699ff', alignSelf: 'stretch', } };上面的代码在手机上运行的效果如下图:
class Test extends Component { render() { return ( <View style={styles.container}> <Text style={[styles.block, styles.text]}></Text> <Text style={[styles.block, styles.text]}></Text> <Text style={[styles.block, styles.text]}></Text> <Text style={[styles.block, styles.text]}></Text> <Text style={[styles.block, styles.text]}></Text> </View> ); } } const styles = { container: { flex: 1, justifyContent: 'flex-start', }, text: { fontSize: 13, color: '#ff0000', marginTop: 10, }, block: { width: 150, height: 40, backgroundColor: '#6699ff', } };以上代码在手机上的运行效果如下图: