返回
React Native Flex布局:70个实用栗子助力您的项目开发
前端
2023-10-01 17:00:26
前言:掌握Flex布局,提升开发效率
Flex布局是一种基于盒模型的布局方式,可让您轻松创建复杂、响应式的布局。它在React Native开发中非常有用,因为React Native应用程序通常需要适应各种屏幕尺寸和设备。通过使用Flex布局,您可以轻松地创建可自动调整大小的布局,以适应不同设备的屏幕尺寸。
1. 单列布局
<View style={{ flexDirection: 'column' }}>
<View style={{ flex: 1, backgroundColor: 'red' }} />
<View style={{ flex: 1, backgroundColor: 'green' }} />
<View style={{ flex: 1, backgroundColor: 'blue' }} />
</View>
2. 多列布局
<View style={{ flexDirection: 'row' }}>
<View style={{ flex: 1, backgroundColor: 'red' }} />
<View style={{ flex: 1, backgroundColor: 'green' }} />
<View style={{ flex: 1, backgroundColor: 'blue' }} />
</View>
3. 流式布局
<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
<View style={{ flex: 1, backgroundColor: 'red' }} />
<View style={{ flex: 1, backgroundColor: 'green' }} />
<View style={{ flex: 1, backgroundColor: 'blue' }} />
</View>
4. 垂直居中
<View style={{ flex: 1, justifyContent: 'center' }}>
<View style={{ backgroundColor: 'red' }} />
</View>
5. 水平居中
<View style={{ flex: 1, alignItems: 'center' }}>
<View style={{ backgroundColor: 'red' }} />
</View>
6. 伸缩布局
<View style={{ flex: 1 }}>
<View style={{ flex: 1, backgroundColor: 'red' }} />
<View style={{ flex: 2, backgroundColor: 'green' }} />
<View style={{ flex: 3, backgroundColor: 'blue' }} />
</View>
7. 嵌套布局
<View style={{ flex: 1 }}>
<View style={{ flexDirection: 'row' }}>
<View style={{ flex: 1, backgroundColor: 'red' }} />
<View style={{ flex: 2, backgroundColor: 'green' }} />
</View>
<View style={{ flexDirection: 'row' }}>
<View style={{ flex: 1, backgroundColor: 'blue' }} />
<View style={{ flex: 2, backgroundColor: 'yellow' }} />
</View>
</View>
8. 绝对定位
<View style={{ flex: 1 }}>
<View style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'red' }} />
</View>
9. 相对定位
<View style={{ flex: 1 }}>
<View style={{ position: 'relative', top: 100, left: 100, backgroundColor: 'red' }} />
</View>
10. Flexbox 容器属性
<View style={{
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
alignItems: 'center',
}}
>
<View style={{ backgroundColor: 'red' }} />
<View style={{ backgroundColor: 'green' }} />
<View style={{ backgroundColor: 'blue' }} />
</View>