let NextID: number = 1;
// 使用装饰器监听数组对象
@Observed
class Info {
public id: number;
public info: number;
constructor(info: number) {
this.id = NextID++;
this.info = info;
}
}
// ObjectLink一定要放在子组件里面
@Component
struct Child {
// 子组件Child的@ObjectLink的类型是Info
@ObjectLink info: Info;
label: string = 'ViewChild';
build() {
Row() {
Button(`ViewChild [${this.label}] this.info.info = ${this.info ? this.info.info : "undefined"}`)
.width(320)
.margin(10)
.onClick(() => {
this.info.info += 1;
})
}
}
}
@Entry
@Component
struct Parent {
// 即使是在函数之中请求的数据,赋值时也要使用 new ,否则监听不到函数变化
// Parent中有@State装饰的Info[]
@State arrA: Info[] = [new Info(0), new Info(0)];
build() {
Column() {
ForEach(this.arrA,
(item: Info) => {
Child({ label: `#${item.id}`, info: item })
},
(item: Info): string => item.id.toString()
)
// 使用@State装饰的数组的数组项初始化@ObjectLink,其中数组项是被@Observed装饰的Info的实例
Child({ label: `ViewChild this.arrA[first]`, info: this.arrA[0] })
Child({ label: `ViewChild this.arrA[last]`, info: this.arrA[this.arrA.length-1] })
Button(`ViewParent: reset array`)
.width(320)
.margin(10)
.onClick(() => {
this.arrA = [new Info(0), new Info(0)];
})
Button(`ViewParent: push`)
.width(320)
.margin(10)
.onClick(() => {
this.arrA.push(new Info(0))
})
Button(`ViewParent: shift`)
.width(320)
.margin(10)
.onClick(() => {
if (this.arrA.length > 0) {
this.arrA.shift()
} else {
console.log("length <= 0")
}
})
Button(`ViewParent: item property in middle`)
.width(320)
.margin(10)
.onClick(() => {
this.arrA[Math.floor(this.arrA.length / 2)].info = 10;
})
Button(`ViewParent: item property in middle`)
.width(320)
.margin(10)
.onClick(() => {
this.arrA[Math.floor(this.arrA.length / 2)] = new Info(11);
})
}
}
}
评论