HarmonyOS 对象数组在@state修饰时,对象属性变化界面不刷新的解决办法

HarmonyOS
2025-01-09 15:31:55
886浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

示例参考:

@Observed
export class PlateColorItem {
  id: string = '';
  isSelected: boolean = false;
  selectedColor: Color | string = ''
  title: string = ''

  constructor(id: string, isSelected: boolean = false, selectedColor: Color | string, title: string,) {
    this.id = id;
    this.isSelected = isSelected;
    this.selectedColor = selectedColor;
    this.title = title;
  }

  // function: (){}
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State
  plateColorItems: PlateColorItem[] = [
    new PlateColorItem('1', false, Color.Blue, '蓝牌'),
    new PlateColorItem('2', false, '#33E099', '绿牌'),
    new PlateColorItem('3', false, Color.Orange, '黄牌'),
    new PlateColorItem('4', false, '#12CCC0', '其他'),
  ];

  build() {
    Column() {
      test({ test: this.plateColorItems[3] })
    }
  }
}

@Component
struct test {
  @ObjectLink test: PlateColorItem

  build() {
    Text('hhhhh')
      .fontSize(px2vp(50))//.lineHeight(px2vp(54))
      .width(px2vp(200))
      .height(px2vp(114))
      .borderRadius(px2vp(7))
      .backgroundColor(this.test.isSelected ? Color.Orange : Color.Blue)
      .textAlign(TextAlign.Center)
      .onClick(() => {
        this.test.isSelected = true;
        // console.log("ddd"+this.plateColorItems);
      })
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.

也可以看下试用版的@ObservedV2装饰器和@Trace装饰器:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-new-observedv2-and-trace-V5

分享
微博
QQ
微信
回复
2025-01-09 16:30:34
相关问题
HarmonyOS @State可以修饰对象数组
690浏览 • 1回复 待解决
HarmonyOS @state可以修饰对象数组
663浏览 • 1回复 待解决
@State 修饰变量值改变,界面刷新
2537浏览 • 1回复 待解决
如何监听数组对象属性变化
3144浏览 • 1回复 待解决
HarmonyOS 数组对象数据刷新
851浏览 • 1回复 待解决
修改ForEach使用数据对象,UI刷新
2971浏览 • 1回复 待解决