組件可以使用flexbox算法指定其子級的布局喇嘱。 Flexbox旨在為不同的屏幕尺寸提供一致的布局。
您通常會使用flexDirection,alignItems和justifyContent的組合來實現正確的布局。
除了一些例外情況,Flexbox在React Native中的工作方式與在Web上的CSS工作方式相同捏顺。默認值是不同的,flexDirection默認為列而不是行碳竟,而flex參數只支持單個數字草丧。
Flex Direction
將flexDirection添加到組件的樣式將確定其布局的主軸。子元素應該水平(行)還是垂直(列)組織莹桅?默認是列昌执。
import React, { Component } from 'react';
import { View } from 'react-native';
export default class FlexDirectionBasics extends Component {
render() {
return (
// Try setting `flexDirection` to `column`.
<View style={{flex: 1, flexDirection: 'row'}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View>
);
}
};
row
column
Justify Content
將justifyContent添加到組件的樣式可確定沿主軸的子元素分布。子元素是否應該在開始诈泼,中間懂拾,結束或分配均勻?可用的選項是flex-start铐达,center岖赋,flex-end,space-around和space-between瓮孙。
import React, { Component } from 'react';
import { View } from 'react-native';
export default class JustifyContentBasics extends Component {
render() {
return (
// Try setting `justifyContent` to `center`.
// Try setting `flexDirection` to `row`.
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View>
);
}
};
Align Items
將alignItems添加到組件的樣式將確定子軸沿著輔助軸的對齊方式(如果主軸是行唐断,則輔助是列选脊,反之亦然)。兒童是否應該在開始脸甘,中間恳啥,結束或延伸填補?可用的選項是flex-start丹诀,center钝的,flex-end和stretch。
為了有效地拉伸铆遭,子元素的副軸不能有固定的尺寸硝桩。在以下示例中,設置alignItems:stretch將不執(zhí)行任何操作枚荣,直到寬度:50從子項中移除碗脊。
import React, { Component } from 'react';
import { View } from 'react-native';
export default class AlignItemsBasics extends Component {
render() {
return (
// Try setting `alignItems` to 'flex-start'
// Try setting `justifyContent` to `flex-end`.
// Try setting `flexDirection` to `row`.
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View>
);
}
};