#鸿蒙通关秘籍#如何利用@Observed装饰器和@ObjectLink装饰器实现多层嵌套类对象属性的变化监听?

HarmonyOS
2024-12-09 13:42:22
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
一路向北545
@Observed
class DateClass extends Date {
  constructor(args: number | string) {
    super(args)
  }
}

@Observed
class NewDate {
  public data: DateClass;

  constructor(data: DateClass) {
    this.data = data;
  }
}

@Component
struct Child {
  label: string = 'date';
  @ObjectLink data: DateClass;

  build() {
    Column() {
      Button(`child increase the day by 1`)
        .onClick(() => {
          this.data.setDate(this.data.getDate() + 1);
        })
      DatePicker({
        start: new Date('1970-1-1'),
        end: new Date('2100-1-1'),
        selected: this.data
      })
    }
  }
}

@Entry
@Component
struct Parent {
  @State newData: NewDate = new NewDate(new DateClass('2023-1-1'));

  build() {
    Column() {
      Child({ label: 'date', data: this.newData.data })

      Button(`parent update the new date`)
        .onClick(() => {
          this.newData.data = new DateClass('2023-07-07');
        })
      Button(`ViewB: this.newData = new NewDate(new DateClass('2023-08-20'))`)
        .onClick(() => {
          this.newData = new NewDate(new DateClass('2023-08-20'));
        })
    }
  }
}



​https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-observed-and-objectlink-V5​

分享
微博
QQ
微信
回复
2024-12-14 21:17:04
相关问题
HarmonyOS 装饰数据变化监听
34浏览 • 1回复 待解决
HarmonyOS @Observed装饰问题咨询
203浏览 • 1回复 待解决