build() {
Column() {
ViewA({ label: ‘ViewA #1’, a: this.b.a })
ViewA({ label: ‘ViewA #2’, a: this.b.a })
Button(ViewB: this.b.a.c+= 1
)
.onClick(() => {
this.b.a.c += 1;
})
Button(ViewB: this.b.a = new ClassA(0)
)
.onClick(() => {
this.b.a = new ClassA(0);
})
Button(ViewB: this.b = new ClassB(ClassA(0))
)
.onClick(() => {
this.b = new ClassB(new ClassA(0));
})
}
}
}
复制
ViewB中的事件句柄:
- this.b.a = new ClassA(0) 和this.b = new ClassB(new ClassA(0)): 对@State装饰的变量b和其属性的修改。
- this.b.a.c = … :该变化属于第二次的变化,@State无法观察到第二层的变化,但是ClassA被@Observed装饰,ClassA的属性c的变化可以被@ObjectLink观察到。
ViewA中的事件句柄:
- this.a.c += 1:对@ObjectLink变量a的修改,将触发Button组件的刷新。@ObjectLink和@Prop不同,@ObjectLink不拷贝来自父组件的数据源,而是在本地构建了指向其数据源的引用。
- @ObjectLink变量是只读的,this.a = new ClassA(…)是不允许的,因为一旦赋值操作发生,指向数据源的引用将被重置,同步将被打断。
对象数组
对象数组是一种常用的数据结构。以下示例展示了数组对象的用法。
@Component
struct ViewA {
// 子组件ViewA的@ObjectLink的类型是ClassA
@ObjectLink a: ClassA;
label: string = ‘ViewA1’;
build() {
Row() {
Button(ViewA [${this.label}] this.a.c = ${this.a.c} +1
)
.onClick(() => {
this.a.c += 1;
})
}
}
}
@Entry
@Component
struct ViewB {
// ViewB中有@State装饰的ClassA[]
@State arrA: ClassA[] = [new ClassA(0), new ClassA(0)];
build() {