前置知识: HarmonyOS

ArkUI声明式语法

1 minAdvanced2026/6/14

HarmonyOS ArkUI声明式语法详解:@Component、@Entry、@State、@Prop、@Link。

1. 核心装饰器

装饰器说明
@Component声明自定义组件
@Entry标记页面入口
@State组件内状态(可变)
@Prop父组件单向传递
@Link父子双向绑定
@Provide跨层级提供数据
@Consume跨层级消费数据
@Watch监听状态变化
@Builder轻量 UI 复用

2. @State

@Entry
@Component
struct Counter {
  @State count: number = 0

  build() {
    Column() {
      Text(`Count: ${this.count}`)
      Button('+1')
        .onClick(() => this.count++)
    }
  }
}
// 父组件
@Entry
@Component
struct Parent {
  @State value: number = 0

  build() {
    Column() {
      Child({ count: this.value })       // @Prop 单向
      ChildLink({ count: $value })       // @Link 双向
    }
  }
}

// 子组件 - @Prop
@Component
struct Child {
  @Prop count: number  // 只读,父组件变化时更新

  build() { Text(`${this.count}`) }
}

// 子组件 - @Link
@Component
struct ChildLink {
  @Link count: number  // 可修改,双向同步

  build() {
    Button('+1').onClick(() => this.count++)
  }
}

4. @Builder

@Builder function ItemView(text: string) {
  Row() {
    Text(text).fontSize(16)
  }.padding(10)
}

// 使用
build() {
  Column() {
    ItemView('Item 1')
    ItemView('Item 2')
  }
}