4.1.2 Flex 弹性布局
Flex 布局包括两个东西,一个叫做容器,还有一个叫做 Flex 元素。如图4-2所示:
图4-2 容器和元素
容器样式
容器主要有 5 个样式键:
- flexDirection
- flexWrap
- justify-content
- alignItems
- align-content
flexDirection: flexDirection 键决定了组件元素是如何排列的,取值可以为: row,column 如图4-3所示,类似Android中 LinearLayout 的 orientation 属性。 RN 还支持 row-reverse 和 column-reverse,反方向布局。
图4-3 flexDirection
flexWrap:
flexWrap 样式键,可选 wrap 和 nowrap (默认值)
水平或垂直布局时,如果元素在一行或者一列显示不全时是否自动换行,默认为 nowrap (不换行) 如图4-4所示。
图4-4 flexWrap
justifyContent:
设置子布局在主轴方向位置 ,当 flexDirection 为 row 的时候主轴为水平,反之则是垂直。
justifyContent 取值包括: flex-start,flex-end,center,space-between,space-around。效果参考图4-5。
图4-5 justifyContent
alignItems
定义了 View 组件中所有子组件的对齐规则。有4种可能的字符串类型的值:
- flex-start 顶部对齐
- flex-end 底部对齐
- center 中部对齐
- stretch 拉长对齐(默认值)
效果如图4-6所示:
图4-6 alignItems
修改 src/pages/CartPage.js
,演示用法:
type Props = {};
export default class CartPage extends Component<Props> {
render() {
return ( // 渲染布局
<View style={styles.container}>
<View style={{margin:10,width:40,height:50,backgroundColor:'red'}}/>
<View style={{margin:10,width:60,height:50,backgroundColor:'green'}}/>
<View style={{margin:10,width:80,height:50,backgroundColor:'blue'}}/>
<View style={{margin:10,width:100,height:50,backgroundColor:'black'}}/>
<View style={{margin:10,width:100,height:50,backgroundColor:'orange'}}/>
<View style={{margin:10,width:40,height:50,backgroundColor:'pink'}}/>
</View>
);
}
}
// 样式文件
const styles = StyleSheet.create({
container: {
paddingTop:theme.barContentPad,
flexDirection:'row',
flexWrap:'wrap',
justifyContent:'space-around',
backgroundColor: '#F5FCFF'
}
});
元素样式
flex 权重,类似 Android 中的 weight。flex 键的类型是数值,默认值是0,当它的值为1时,子组件将自动缩放以适应父组件剩下的空白空间。
使用flex键时一定要小心,它的自动缩放意味着不仅可以改变自己的宽、高与位置,还可以通过挤压改变与它同级的其他组件的位置。
设置了 flex:1 的组件不是只能扩展,如果同级别固定宽高的组件在执行宽高增加了,那么设置 flex:1 的组件就会缩小来适应同级组件的宽和高变化。如图4-7 所示。
图4-7 flex
alignSelf:
alignSelf 键有5种可能的字符串类型值:auto、flex-start、flex-end、center、stretch。其用途是让组件忽略它的父组件样式中的alignItems 的取值,而对该组件使用 alignSelf 键对应的规则。当它取值为 auto 时,表示使用父 View 组件的 alignItems 值。如图4-8所示。
图4-8 alignSelf