ArkTS/ArkUI实战

九、鸿蒙ArkTS/ArkUI实战-装饰器@Observed和@

2023-11-20  本文已影响0人  ISwiftUI
@Observed class ClassA {}
@ObjectLink a: ClassA
使用要求

代码示例:

@Observed
class ClassA {
  public name : string;
  public c: number;
  constructor(c: number, name: string = '') {
    this.name = name;
    this.c = c;
  }
}
 
class ClassB {
  public a: ClassA;
  constructor(a: ClassA) {
    this.a = a;
  }
}
 
@Component
struct ViewA {
  label : string = "ep1";
  @ObjectLink a : ClassA;
  build() {
    Column() {
      Text(`ViewA [${this.label}]: a.c=${this.a.c}`)
        .fontSize(20)
      Button(`+1`)
        .width(100)
        .margin(2)
        .onClick(() => {
          this.a.c += 1;
        })
      Button(`reset`)
        .width(100)
        .margin(2)
        .onClick(() => {
          this.a = new ClassA(0); // 错误:ObjectLink装饰的变量a是不可变的
        })
    }
  }
}
 
@Entry
@Component
struct ViewB {
  @State b : ClassB = new ClassB(new ClassA(10));
  build() {
    Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center}) {
      ViewA({label: "ViewA #1", a: this.b.a})
      ViewA({label: "ViewA #2", a: this.b.a})
 
      Button(`ViewB: this.b.a.c += 1` )
        .width(320)
        .margin(4)
        .onClick(() => {
          this.b.a.c += 1;
        })
      Button(`ViewB: this.b.a = new ClassA(0)`)
        .width(240)
        .margin(4)
        .onClick(() => {
          this.b.a = new ClassA(0);
        })
      Button(`ViewB: this.b = new ClassB(ClassA(0))`)
        .width(240)
        .margin(4)
        .onClick(() => {
          this.b = new ClassB(new ClassA(0));
        })
    }
  }
}
上一篇 下一篇

猜你喜欢

热点阅读