点击之后并没有更新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)
}
}
}
请参考此demo:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-observed-and-objectlink-V5\#嵌套对象