Skip to content

状态管理

状态管理是构建复杂应用的核心,HarmonyOS 提供了多种状态管理方案。

组件内状态

@State

@State 装饰器用于声明组件的内部状态,当状态改变时会自动触发 UI 更新。

typescript
@Component
struct Counter {
  @State count: number = 0
  
  build() {
    Column() {
      Text(`Count: ${this.count}`)
        .fontSize(24)
      
      Button('Increment')
        .onClick(() => {
          this.count++ // 自动触发 UI 更新
        })
    }
  }
}

特点:

  • 只能在组件内部使用
  • 变化会触发 UI 重新渲染
  • 支持基本类型和复杂对象

(内容继续...)

全栈若城