@State是OpenHarmony ArkUI中最重要的装饰器之一。它的核心逻辑是:
当被@State修饰的变量发生变化时,所有依赖这个变量的UI组件都会自动重新渲染。
我们通过一个简单的计数器来演示这个机制,代码量很少,但充分体现了"状态驱动视图"。

@Entry
@Component
struct Index {
  // @State修饰的变量,变化时会触发UI刷新
  @State count: number = 0;

  build() {
    Column({ space: 20 }) {
      // 显示当前计数值 - 依赖count状态
      Text(`当前计数: ${this.count}`)
        .fontSize(40)
        .fontWeight(FontWeight.Bold)
        .fontColor('#333333')

      // 显示奇偶性 - 同样依赖count状态,会自动计算
      Text(this.count % 2 === 0 ? '偶数' : '奇数')
        .fontSize(24)
        .fontColor(this.count % 2 === 0 ? '#007DFF' : '#FF6B6B')

      Row({ space: 30 }) {
        // 减少按钮
        Button('-')
          .fontSize(30)
          .width(60)
          .height(60)
          .backgroundColor('#FF6B6B')
          .onClick(() => {
            // 修改@State变量,UI自动更新
            this.count--;
          })
        Button('重置')
          .fontSize(20)
          .width(80)
          .height(60)
          .backgroundColor('#FFA94D')
          .onClick(() => {
            this.count = 0;
          })

        Button('+')
          .fontSize(30)
          .width(60)
          .height(60)
          .backgroundColor('#51CF66')
          .onClick(() => {
            this.count++;
          })
      }

      // 进度条 - 展示count在0-10之间的进度
      Progress({
        value: this.count,
        total: 10,
        type: ProgressType.Linear
      })
        .width('80%')
        .height(20)
        .color('#007DFF')
        .backgroundColor('#E9ECEF')
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
    .backgroundColor('#F8F9FA')
  }
}

1. 状态声明

@State count: number = 0;

@State告诉框架:这是一个可观测的状态变量
当count的值改变时,框架会自动追踪并更新所有使用到count的UI
初始值设为0

2. 状态使用(自动依赖追踪)

Text(`当前计数: ${this.count}`)
  .fontSize(40)

直接在UI中使用this.count,框架会自动建立依赖关系
每个Text组件都"订阅"了count的变化

Text(this.count % 2 === 0 ? '偶数' : '奇数')

甚至可以依赖状态进行计算
count变化时,这个表达式会重新求值,UI同步更新

3. 状态修改(触发更新)

.onClick(() => {
  this.count++;  // 这行代码触发一切
})

在按钮点击事件中直接修改this.count
不需要调用任何刷新方法,UI自动更新

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐