Skip to content

React Native - Flexbox 布局

React Native 使用 Flexbox 在不同屏幕尺寸上提供一致的布局模型。Flexbox 设计用于管理容器中项目(items)之间的空间分布,即使它们的尺寸未知或动态变化。

我们将使用一个简单的组件来演示 Flexbox 的属性。

核心布局属性 (Core Layout Properties)

Section titled “核心布局属性 (Core Layout Properties)”

为了实现所需的布局,Flexbox 主要在容器上使用 flexDirection、justifyContent 和 alignItems 属性。flex 属性用于子项目 (child items) 上,定义它们伸展或收缩的能力。

属性 (Property)常用值 (Values - Common)描述 (Description)
flexDirection’column’ (默认), ‘row’, ‘column-reverse’, ‘row-reverse’定义项目沿哪条主轴 (primary axis) 排列。‘column’ 垂直堆叠项目,‘row’ 水平排列项目。
justifyContent’flex-start’, ‘flex-end’, ‘center’, ‘space-between’, ‘space-around’, ‘space-evenly’沿主轴(由 flexDirection 定义)对齐项目。
alignItems’flex-start’, ‘flex-end’, ‘center’, ‘stretch’ (默认), ‘baseline’沿交叉轴(垂直于 flexDirection)对齐项目。
flex一个数字(例如 1, 2)应用于子项目。决定项目沿主轴相对于容器中其他项目应占用多少空间。值为 1 表示它将按比例占用可用空间。
alignSelf’auto’, ‘flex-start’, ‘flex-end’, ‘center’, ‘stretch’, ‘baseline’应用于某个子项目,以覆盖父容器对该特定项目的 alignItems 属性。

示例 1:垂直居中并水平居中对齐项目:

App.js

<html>
<body>
<p>
import React from 'react';
import { StyleSheet, View } from 'react-native';
const App = () => {
return (
&lt;View style={styles.container}&gt;
&lt;View style={styles.redBox} /&gt;
&lt;View style={styles.blueBox} /&gt;
&lt;View style={styles.blackBox} /&gt;
&lt;/View&gt;
);
};
const styles = StyleSheet.create({
container: {
flex: 1, // Takes up all available space
flexDirection: 'column', // Default, items stacked vertically
justifyContent: 'center', // Center items vertically
alignItems: 'center', // Center items horizontally
backgroundColor: 'grey',
},
redBox: {
width: 100,
height: 100,
backgroundColor: 'red',
marginBottom: 10, // Added for spacing
},
blueBox: {
width: 100,
height: 100,
backgroundColor: 'blue',
marginBottom: 10, // Added for spacing
},
blackBox: {
width: 100,
height: 100,
backgroundColor: 'black',
},
});
export default App;
</p>
</body>
</html>

输出:此代码将显示三个不同颜色的方框(红、蓝、黑),它们垂直堆叠在屏幕中央,同时也在水平方向居中。每个方框下方都有一个小外边距用于分隔。

示例 2:水平排列项目,间隔均匀,并对齐到顶部:

App.js

<html>
<body>
<p>
import React from 'react';
import { StyleSheet, View } from 'react-native';
const App = () => {
return (
&lt;View style={styles.container}&gt;
&lt;View style={styles.redBox} /&gt;
&lt;View style={styles.blueBox} /&gt;
&lt;View style={styles.blackBox} /&gt;
&lt;/View&gt;
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row', // Items arranged horizontally
justifyContent: 'space-around', // Distribute space around items
alignItems: 'flex-start', // Align items to the top of the container
backgroundColor: 'lightgrey',
paddingTop: 50, // Add some padding at the top
},
redBox: {
width: 80,
height: 80,
backgroundColor: 'red',
},
blueBox: {
width: 80,
height: 80,
backgroundColor: 'blue',
},
blackBox: {
width: 80,
height: 80,
backgroundColor: 'black',
},});
export default App;
</p>
</body>
</html>

输出:此代码将显示三个较小的彩色方框(红、蓝、黑),它们水平排列在屏幕顶部附近。它们将在水平轴上均匀分布空间。

要获得更深入的理解和交互式示例,请访问 React Native 官方文档的 Layout with Flexbox 或像 Yoga Playground 这样的资源(Yoga 是 React Native 背后的布局引擎)。