鸿蒙 ArkTS 七大布局组件详解
1. Column 垂直线性布局作用子组件从上至下垂直排列页面最常用基础容器。核心参数space子组件间距justifyContent垂直分布alignItems水平对齐示例代码Entry Component struct ColumnDemo { build() { Column({ space: 15 }) { Text(标题) .fontSize(20) Text(正文内容) Button(提交) } .width(100%) .padding(20) .justifyContent(FlexAlign.Center) // 垂直居中 .alignItems(HorizontalAlign.Start) // 左对齐 } }2. Row 水平线性布局作用子组件从左至右水平排列实现一行多元素排版。核心参数space元素间距主轴 / 交叉轴对齐属性同 Column示例代码Entry Component struct RowDemo { build() { Row({ space: 10 }) { Text(选项1) .width(80) .height(40) .backgroundColor(#eee) Text(选项2) .width(80) .height(40) .backgroundColor(#eee) Text(选项3) .width(80) .height(40) .backgroundColor(#eee) } .width(100%) .padding(10) } }3. Stack 层叠布局作用子组件叠加堆叠后写组件覆盖上层适合背景 浮层、角标场景。核心参数alignContent统一对齐子组件.zIndex()控制层级数值越大越顶层示例代码Entry Component struct StackDemo { build() { Stack({ alignContent: Alignment.Center }) { // 底层背景 Rect() .width(200) .height(120) // 中层文字 Text(主图) .fontSize(22) .fontColor(Color.White) .zIndex(1) // 顶层角标 Text(热) .fontSize(12) .backgroundColor(Color.Red) .fontColor(Color.White) .padding(4) .position({ x: 160, y: 10 }) .zIndex(2) } } }4. Flex 弹性布局作用超灵活自适应布局支持自动换行、均分剩余空间复杂流式排版首选。核心参数direction主轴方向wrap是否换行justifyContent主轴分布示例代码Entry Component struct FlexDemo { build() { Flex({ direction: FlexDirection.Row, wrap: FlexWrap.Wrap, // 自动换行 justifyContent: FlexAlign.SpaceAround }) { ForEach([1,2,3,4,5], (item:number){ Text(标签${item}) .width(100) .height(40) .backgroundColor(#f0f0f0) .margin({ bottom:10 }) }) } .width(100%) .padding(10) } }5. RelativeContainer 相对布局作用通过 ID 互相参照定位适合组件位置互相依赖的复杂页面。核心 APIid(xxx)给组件标记.alignRules()设置相对对齐规则示例代码Entry Component struct RelativeDemo { build() { RelativeContainer() .width(300) .height(300) .backgroundColor(#f5f5f5) { // 基准方块 Rect() .id(base) .width(80) .height(80) .fill(#2196F3) .alignRules({ centerX: { anchor: __container__, align: HorizontalAlign.Center }}) // 方块在基准下方 Rect() .id(down) .width(60) .height(60) .fill(#4CAF50) .alignRules({ top: { anchor: base, align: VerticalAlign.Bottom }}) } } }6. Swiper 轮播布局作用横向滑动切换多页面用于首页 Banner、图片轮播。核心参数index默认页loop循环播放autoPlay自动轮播interval切换间隔示例代码Entry Component struct SwiperDemo { State curIndex: number 0 build() { Swiper() { ForEach([1,2,3], (i:number){ Rect() .width(100%) .height(160) .fill(i%2 ? #FF9800:#9C27B0) }) } .index(this.curIndex) .loop(true) .autoPlay(true) .interval(3000) .width(100%) .height(160) } }7. Tabs 标签页布局作用顶部 / 底部切换多内容页面常用于首页分栏、分类导航。核心参数barPosition标签栏位置Start 顶部 / End 底部onChange切换监听示例代码Entry Component struct TabsDemo { build() { Tabs({ barPosition: BarPosition.Start }) { TabContent() { Text(首页内容).fontSize(24) } .tabBar(Text(首页).fontSize(16)) TabContent() { Text(分类内容).fontSize(24) } .tabBar(Text(分类).fontSize(16)) TabContent() { Text(我的页面).fontSize(24) } .tabBar(Text(我的).fontSize(16)) } .width(100%) .height(400) } }快速选型总结简单上下排列 → Column简单左右一行 → Row叠加浮层 / 角标 → Stack流式自动换行 / 均分 → Flex组件互相参照定位 → RelativeContainer图片滑动轮播 → Swiper顶部底部切换页面 → Tabs