ArkUI 组件体系详解

📅 2025-05-16 · ⏱ 20 分钟 · ArkUI

ArkUI 是 HarmonyOS 的声明式 UI 开发框架,提供了一套丰富的组件体系。本文将系统介绍基础组件、容器组件和布局系统的使用方法。

一、基础组件

基础组件是最常用的 UI 元素,用于展示信息或接收用户输入。

1. Text 文本

用于显示一段不可编辑的文本内容。

Text("Hello HarmonyOS")
  .fontSize(20)
  .fontWeight(FontWeight.Bold)
  .fontColor("#333")
  .textAlign(TextAlign.Center)
  .maxLines(2)
  .textOverflow({ overflow: TextOverflow.Ellipsis })

2. Image 图片

支持网络图片、本地资源和 Base64 数据。

Image("https://example.com/photo.jpg")
  .width(200)
  .height(200)
  .objectFit(ImageFit.Cover)
  .borderRadius(12)

3. Button 按钮

按钮组件支持多种样式类型。

Button("点击提交")
  .type(ButtonType.Capsule)
  .backgroundColor("#cf0a2c")
  .fontColor(Color.White)
  .width("90%")
  .height(48)
  .onClick(() => {
    console.log("按钮被点击")
  })

4. TextInput 输入框

@State inputVal: string = ""

TextInput({ placeholder: "请输入用户名", text: this.inputVal })
  .type(InputType.Normal)
  .width("100%")
  .height(48)
  .onChange((value: string) => {
    this.inputVal = value
  })

二、容器组件

容器组件用于组织和排列子组件。

1. Column 纵向排列

Column({ space: 12 }) {
  Text("第一行")
  Text("第二行")
  Text("第三行")
}
.width("100%")
.padding(16)
.alignItems(HorizontalAlign.Center)

2. Row 横向排列

Row({ space: 16 }) {
  Image($r("app.media.avatar"))
    .width(48)
    .height(48)
    .borderRadius(24)
  Column() {
    Text("用户名").fontSize(16).fontWeight(FontWeight.Medium)
    Text("个人简介").fontSize(14).fontColor("#999")
  }
  .alignItems(HorizontalAlign.Start)
}
.width("100%")
.padding(16)

3. List 列表

@State items: string[] = ["项目一", "项目二", "项目三"]

List({ space: 8 }) {
  ForEach(this.items, (item: string) => {
    ListItem() {
      Text(item)
        .width("100%")
        .padding(16)
        .backgroundColor(Color.White)
        .borderRadius(8)
    }
  })
}
.width("100%")
.layoutWeight(1)

4. Tabs 选项卡

@State curIndex: number = 0

Tabs({ index: this.curIndex }) {
  TabContent() {
    Text("首页内容").fontSize(20)
  }.tabBar("首页")

  TabContent() {
    Text("我的内容").fontSize(20)
  }.tabBar("我的")
}
.onChange((index: number) => {
  this.curIndex = index
})

三、布局系统

ArkUI 采用弹性布局(Flex),通过主轴和交叉轴控制子组件排列。

主轴对齐 justifyContent

交叉轴对齐 alignItems

尺寸单位

四、实战:构建一个用户信息卡片

@Entry
@Component
struct UserCard {
  build() {
    Row() {
      Image($r("app.media.avatar"))
        .width(56)
        .height(56)
        .borderRadius(28)

      Column() {
        Text("张三")
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
        Text("HarmonyOS 开发者")
          .fontSize(14)
          .fontColor("#666")
          .margin({ top: 4 })
      }
      .alignItems(HorizontalAlign.Start)
      .layoutWeight(1)
      .margin({ left: 12 })

      Image($r("app.media.ic_arrow"))
        .width(24)
        .height(24)
    }
    .width("100%")
    .padding(16)
    .backgroundColor(Color.White)
    .borderRadius(12)
    .shadow({ radius: 4, color: "#1a000000", offsetY: 2 })
  }
}

五、小结