HarmonyOS Observed一些疑问?

点击之后并没有更新ui

// objectLinkNestedObjects.ets
let NextID: number = 1;

@Observed
class gongSi {
  public user: User
  constructor(user: User) {
    this.user = user
  }
}

@Observed
class Bag {
  public id: number;
  public size: number;

  constructor(size: number) {
    this.id = NextID++;
    this.size = size;
  }
}

@Observed
class User {
  public bag: Bag;

  constructor(bag: Bag) {
    this.bag = bag;
  }
}

@Observed
class Book {
  public bookName: BookName;

  constructor(bookName: BookName) {
    this.bookName = bookName;
  }
}

@Observed
class BookName extends Bag {
  public nameSize: number;

  constructor(nameSize: number) {
    // 调用父类方法对nameSize进行处理
    super(nameSize);
    this.nameSize = nameSize;
  }
}

@Component
struct ViewB {
  label: string = 'ViewB';
  @ObjectLink gongsi: gongSi;

  build() {
    Column() {
      Text(`ViewB [${this.label}] this.bag.size = ${this.gongsi.user.bag.size}`)
        .fontColor('#ffffffff')
        .backgroundColor('#ff3d9dba')
        .width(320)
        .height(50)
        .borderRadius(25)
        .margin(10)
        .textAlign(TextAlign.Center)
      Button(`ViewB: this.bag.size add 1`)
        .width(320)
        .backgroundColor('#ff17a98d')
        .margin(10)
        .onClick(() => {
          this.gongsi.user.bag.size += 1;
        })
    }
  }
}


@Entry
@Component
struct TestPage {
  @State gongsi: gongSi = new gongSi(new User(new Bag(0)))

  build() {
    Column() {
      ViewB({ label: 'ViewB #2', gongsi: this.gongsi })
        .width(320)
    }
  }
}
阅读 473
1 个回答

请参考此demo:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-observed-and-objectlink-V5\#嵌套对象

let NextID: number = 1;

@Observed
class gongSi {
  public user: User
  constructor(user: User) {
    this.user = user
  }
}

@Observed
class Bag {
  public id: number;
  public size: number;

  constructor(size: number) {
    this.id = NextID++;
    this.size = size;
  }
}

@Observed
class User {
  public bag: Bag;

  constructor(bag: Bag) {
    this.bag = bag;
  }
}

@Component
struct ViewB {
  label: string = 'ViewB';
  @ObjectLink bag: Bag;

  build() {
    Column() {
      Text(`ViewB [${this.label}] this.bag.size = ${this.bag.size}`)
        .fontColor('#ffffffff')
        .backgroundColor('#ff3d9dba')
        .width(320)
        .height(50)
        .borderRadius(25)
        .margin(10)
        .textAlign(TextAlign.Center)
      Button(`ViewB: this.bag.size add 1`)
        .width(320)
        .backgroundColor('#ff17a98d')
        .margin(10)
        .onClick(() => {
          this.bag.size += 1;
        })
    }
  }
}

@Entry
@Component
struct TestPage {
  @State gongsi: gongSi = new gongSi(new User(new Bag(0)))

  build() {
    Column() {
      ViewB({ label: 'ViewB #2', bag: this.gongsi.user.bag })
        .width(320)
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进