起点在左
flexDirection:'row'
},
});
效果:
- 现在我们给红色项目设置 flex 为1,可以看到红色项目的宽度填充了除去 绿色项目和黄色项目 的部分
<View style={{backgroundColor:'red', height:60, width:60, flex:1}}></View>
效果:
- 接着再给绿色项目也设置 flex 为1,可以看到红色项目和绿色项目填充了 除黄色项目 的部分,并且红色和绿色项目各占剩下空间的一半
<View style={{backgroundColor:'red', height:60, width:60, flex:1}}></View>
<View style={{backgroundColor:'green', height:60, width:60, flex:1}}></View>
效果:
- 现在我们再设置黄色项目的 flex 为2,可以看出,红色和绿色所占的空间和等同于黄色项目,并且红色和绿色平分了除黄色项目以外的空间,现在我们应该能理解上面公式的意思了吧(项目宽度 = 父项目的宽度 * (子项目自身比例 / 所有父项目内子项目的比例))
<View style={{backgroundColor:'red', height:60, width:60, flex:1}}></View>
<View style={{backgroundColor:'green', height:60, width:60, flex:1}}></View>
<View style={{backgroundColor:'yellow', height:60, width:60, flex:3}}></View>
效果:
- 但是不知道各位发现了没有,虽然我们每个子项目都同时设置了高度和宽度,但是却只有宽度改变,而高度则一直保持我们设置的状态,是不是
flex属性
只对宽度有效呢?接下来我们来修改下代码,看看是不是真的如我们想象的这样 ———— 这里我们将绿色的高度去掉,可以看出,绿色项目的高度填充了整个父项目的高度
<View style={{backgroundColor:'red', height:60, width:60, flex:1}}></View>
<View style={{backgroundColor:'green', width:60, flex:1}}></View>
<View style={{backgroundColor:'yellow', height:60, width:60, flex:3}}></View>
效果:
- 总结以上的示例,可以看出,不管是否设置子项目的宽度,flex都会忽略宽度,按照上面的
公式
进行缩放,如果我们设置了高度,那么 flex 会遵循我们所设置的高度,不去进行拉伸,反之将会对高度进行拉伸
- 根据 flex 的特性,如果没有设置 View 的尺寸情况下,使用 flex 也可以让 View 占满整个屏幕
container: {
backgroundColor:'blue',
flex:1
},
alignSelf(允许单个项目有与其它项目不一样的对齐方式,可覆盖 align-items属性)
- auto(默认):继承父元素的alignItems属性,如果没有则切换为stretch
subViewStyle2: {
backgroundColor:'yellow',
height:60,
width:60,
alignSelf:'auto'
},
效果:
subViewStyle2: {
backgroundColor:'yellow',
height:60,
width:60,
alignSelf:'flex-start'
},
效果:
subViewStyle2: {
backgroundColor:'yellow',
height:60,
width:60,
alignSelf:'flex-end'
},
效果:
subViewStyle2: {
backgroundColor:'yellow',
height:60,
width:60,
alignSelf:'center'
},
效果:
subViewStyle2: {
backgroundColor:'yellow',
height:60,
width:60,
alignSelf:'stretch'
},
效果:
我们 FlexBox 的使用就先简单介绍到这里,在后续的文章中,会在实际的开发场景中带大家更多更细致地讲解 FlexBox,如果你觉得哪里写得不好或者有误,麻烦留言或者用邮箱的方式联系我,当然遇到问题也可以,最后如果喜欢我的文章,还请点个赞并关注,读者的肯定是对我们笔者最大的鼓励,谢谢!