React Native通过一个基于FlexBox的布局引擎,在所有移动平台上实现了一致的跨平台样式和布局方案。
FlexBox布局目前支持的属性有如下6个:
(1)flex
(2)flexDirection
(3)alignSelf
(4)alignItems
(5)justifyContent
(6)flexWrap
接下来,我们一个一个的看一下每个属性的作用。
(1)flex属性
当一个元素定义了flex属性时,表示该元素是可伸缩的(flex的属性值大于0的时候才可伸缩)。
var Demo = React.createClass({ render: function() { return (); } }); var styles = StyleSheet.create({ style_0:{ flex: 1, }, style_1:{ flex: 5, height: 40, borderWidth: 1, borderColor: 'red', } }); 1/4高 1/4高 1/2高
上面的代码,最外层的View是可伸缩的,而且没有兄弟节点和它抢占空间。内层的三个View的flex属性值分别是5、5、10,所以,第一个View和第二个View分别占1 / 4的伸缩空间,最后一个View占1 / 2的伸缩空间。
(2)flexDirection
flexDirection在React Native中只有两个属性值,row(横向伸缩)和column(纵向伸缩)。
var Demo = React.createClass({ render: function() { return (); } }); var styles = StyleSheet.create({ style_0:{ flex: 1, }, style_1:{ flex: 5, flexDirection: 'row', height: 40, borderWidth: 1, borderColor: 'red', } }); 1/4高 1/4高 1/4高 1/4高 1/2高
(3)alignSelf
alignSelf的对齐方式主要有四种:flex-start、flex-end、center、auto、stretch。
var Demo = React.createClass({ render: function() { return (); } }); var styles = StyleSheet.create({ style_0:{ flex: 1, borderColor: 'red', borderWidth: 1 }, view:{ borderWidth: 5, borderColor: 'blue', marginTop: 40, width: 100, height: 40 }, center:{ alignSelf: 'center' }, left:{ alignSelf: 'flex-start' }, right:{ alignSelf: 'flex-end' } }); 自由摆放 居中摆放 居左摆放 居右摆放
(4)alignItems
alignItems是alignSelf的变种,跟alignSelf的功能类似,可用于水平居中。justifyContent用于垂直居中。
var Demo = React.createClass({ render: function() { return (); } }); var styles = StyleSheet.create({ style_0:{ flex: 1, borderColor: 'red', borderWidth: 1, justifyContent: 'center', alignItems: 'center' }, view:{ borderWidth: 3, borderColor: 'blue', width: 100, height: 50 } }); 居中摆放