#跟着若城学鸿蒙# Flex 组件入门与方向布局
·
在 ArkUI 中,Flex
容器借鉴 Web 中的 Flexbox 概念,提供了一套非常灵活的、基于主轴(Main Axis)和纵轴(Cross Axis)的布局方案。本篇将介绍 Flex
的基础定义与方向属性,让你快速掌握如何控制子组件的排列方向。
一、什么是 Flex?
Flex
容器可以看作是一个多功能的、可配置的线性布局器。它既能水平布局,也能垂直布局;在超出容器时可换行;还能通过各种对齐方式细粒度地控制元素位置。相比单纯的 Row
/Column
,Flex
在复杂 UI 场景下更具优势。
1.1 定义
interface FlexInterface {
(options?: FlexOptions): FlexAttribute;
}
declare interface FlexOptions {
direction?: FlexDirection;
wrap?: FlexWrap;
justifyContent?: FlexAlign;
alignItems?: ItemAlign;
alignContent?: FlexAlign;
}
- direction:主轴方向(即排列方向)。
- wrap:是否允许子组件超出并换行/列。
- justifyContent:沿主轴(direction)上分布方式。
- alignItems:沿纵轴(垂直于 direction)上单行/列内对齐方式。
- alignContent:多行/列换行后,纵轴空间分布方式。
二、主轴与纵轴
-
主轴(Main Axis):由
direction
决定。Row
:水平从左到右。Column
:竖直从上到下。
-
纵轴(Cross Axis):与主轴垂直。
理解这两条轴线是灵活使用 justifyContent
与 alignItems
的关键。
三、方向属性(direction)
enum FlexDirection {
Row,
RowReverse,
Column,
ColumnReverse,
}
- Row(默认):子组件水平自左向右排列。
- RowReverse:子组件水平自右向左排列。
- Column:子组件竖直自上而下排列。
- ColumnReverse:子组件竖直自下而上排列。
3.1 Row(水平排列)
Flex({ direction: FlexDirection.Row })
.size({ width: '100%', height: 60 })
.backgroundColor(Color.Pink)
{
Text('Item 1').padding(10).backgroundColor('#aabbcc');
Text('Item 2').padding(10).backgroundColor('#bbaacc');
Text('Item 3').padding(10).backgroundColor('#ccaabb');
Text('Item 4').padding(10).backgroundColor('#abcabc');
}
应用场景:导航栏、水平菜单、按钮组等。
3.2 RowReverse(反向水平)
Flex({ direction: FlexDirection.RowReverse })
.size({ width: '100%', height: 60 })
.backgroundColor(Color.Pink)
{
/* 子组件会从右向左依次排列 */
/* 适合在 RTL(右到左)界面或需要反向排列时使用 */
}
3.3 Column(竖直排列)
Flex({ direction: FlexDirection.Column })
.size({ width: '100%', height: 220 })
.backgroundColor(Color.Pink)
{
/* 子组件自上往下排列 */
}
应用场景:列表、纵向表单、消息流等。
3.4 ColumnReverse(反向竖直)
Flex({ direction: FlexDirection.ColumnReverse })
.size({ width: '100%', height: 220 })
.backgroundColor(Color.Pink)
{
/* 自下往上排列 */
/* 可用于消息倒序展示、聊天记录底部加载等 */
}
四、最佳实践与性能
- **首选
Row/Column
**:对于单行或单列布局,Row
/Column
更简洁高效。 - 使用
Flex
实现复杂布局:当需要多方向切换、换行或对齐细粒度控制时,使用Flex
。 - 避免深层嵌套:多层
Flex
嵌套可能影响渲染性能,建议在同一层通过alignContent
和wrap
实现。 - 响应式考虑:结合
layoutWeight
和百分比宽高,适配不同屏幕尺寸。
更多推荐
所有评论(0)