#鸿蒙通关秘籍#如何避免在鸿蒙开发中使用状态变量强行更新组件?

HarmonyOS
2024-12-02 15:40:36
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
雪域寻踪BIOS

在ArkUI中,避免使用自定义UI状态变量来更新与非状态变量关联的组件,而应该使用框架的状态管理机制。通过使用@State装饰器,将需要更新的变量转化为状态变量,以自然触发UI更新。

@Entry
@Component
struct CompA {
  @State realState1: Array<number> = [4, 1, 3, 2];
  @State realState2: Color = Color.Yellow;

  build() {
    Column({ space: 20 }) {
      ForEach(this.realState1, (item: Array<number>) => {
        Text(`${item}`)
      })
      Text("add item")
        .onClick(() => {
          this.realState1.push(this.realState1[this.realState1.length-1] + 1);
        })
      Text("chg color")
        .onClick(() => {
          this.realState2 = this.realState2 == Color.Yellow ? Color.Red : Color.Yellow;
        })
    }.backgroundColor(this.realState2)
    .width(200).height(500)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
分享
微博
QQ
微信
回复
2024-12-02 17:01:09


相关问题
HarmonyOS constraintSize支持状态变量
928浏览 • 1回复 待解决
ArkTS中如何监听状态变量的变化?
1969浏览 • 1回复 待解决
状态变量和常规变量有什么区别?
1232浏览 • 2回复 待解决
HarmonyOS taskpool参数是状态变量crash
651浏览 • 1回复 待解决
HarmonyOS 状态变量不刷新问题
1578浏览 • 1回复 待解决
关于状态变量@state必须知道的事
2173浏览 • 1回复 待解决