React-Native之flexbox布局篇
这篇博客稍微讲解下React-Native中的布局。比较简单。RN的而布局是用css中的flexbox布局,所以布局起来与android传统的布局样式有点像。接下来就结合图片一起来看看。 常用属性讲解RN的flexbox主要有以下几个属性alignItems,alignSelf,flex,flexDirection,flexWrap,justifyContent。 flexDirection该属性用于指定主轴的方向。即指定子view的布局方向。它有两个值可设置。
这个属性很简单,先看row的代码段: render:function(){
return(
<View style={styles.flexStyle}>
<View style= {styles.flexSub}/>
<View style= {styles.flexSub}/>
<View style= {styles.flexSub}/>
<View style= {styles.flexSub}/>
</View>
);
}
…………
var styles = StyleSheet.create({
flexStyle:{
height:600,flexDirection:'row',},flexSub:{
flex:1,height:300,backgroundColor:'#333333',marginRight:10,)}
一个View里有四个小View,小View的底色是黑的,看下效果图: var styles = StyleSheet.create({
flexStyle:{
height:600,flexDirection:'column',flexSub:{
flex:1,height:100,backgroundColor:'#333333',marginBottom:10,)}
看下效果图: alignItems用于定义子组件在垂直方向上的对齐方式。有四个属性可设置:flex-start,flex-end,center,stretch。
首先来看下flex-start,顺便改了下子组件的颜色,代码如下: return(
<View style={styles.flexStyle}>
<View style= {styles.flexSelf1}/>
<View style= {styles.flexSelf2}/>
<View style= {styles.flexSelf3}/>
<View style= {styles.flexSelf4}/>
</View>
);
……
var styles = StyleSheet.create({
flexStyle:{
height:600,flexDirection: 'row',alignItems:'flex-start',height:300,flexSelf1:{
flex:1,backgroundColor:'#ff0000',marginRight:10,flexSelf2:{
flex:1,backgroundColor:'#00ff00',flexSelf3:{
flex:1,backgroundColor:'#0000ff',flexSelf4:{
flex:1,}
});
看下效果图: justifyContent有竖直就水平。justifyContent和alignItems是相对的。它有五个属性可以设置,分别是flex-start,flex-end,center,space-between,space-around。 先看水平居中(center)的,先看下代码: return(
<View style={styles.flexStyle}>
<View style= {styles.flexSub}/>
</View>
);
……
var styles = StyleSheet.create({
flexStyle:{
height:600,width:400,alignItems:'center',justifyContent:'center',flexSub:{
width:100,});
父容器设置了justifyContent:’center’属性,所以理论上子组件应该会水平剧中,来看下是否正确。如下: alignSelf该属性用来设置单独组件的竖直对齐方式,与alignItem有点像。有五个属性可以设置,auto,flex-start,flex-end,center,streth。 return(
<View style={styles.flexStyle}>
<View style= {styles.flexSelf1}/>
<View style= {styles.flexSelf2}/>
<View style= {styles.flexSelf3}/>
<View style= {styles.flexSelf4}/>
</View>
);
……
var styles = StyleSheet.create({
flexStyle:{
height:600,flexDirection:'row',alignSelf:'flex-start',alignSelf:'flex-end',alignSelf:'stretch',alignSelf:'auto',)}
以上几个子View设置了不同的样式 ,看下效果图: flexflex指设置伸缩项目的伸缩样式,可以把它类比成android中的weight属性。 return(
<View style={styles.flexStyle}>
<View style= {styles.flexSelf1}/>
<View style= {styles.flexSelf1}/>
<View style= {styles.flexSelf2}/>
<View style= {styles.flexSelf3}/>
</View>
);
……
var styles = StyleSheet.create({
flexStyle:{
height:600,flex:1,flexSub:{
height:300,flexSelf2:{
flex:2,flexSelf3:{
flex:4,});
效果图如下: flexWrap其实这些属性都是CSS原有的属性,只是RN只支持了部分的属性。flexWrap用于设置是否可换行,有两个属性可设置nowrap和wrap。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |