帮朋友提问:
父组件修改子组件能刷新,子组件修改父组件没反应,那个大佬能帮我看看是不是我代码有问题,还是文档有问题?
@Observed
class ClassA {
public value: number;
constructor(value: number) {
this.value = value;
}
}
class ClassB {
public a: ClassA;
constructor(a: ClassA) {
this.a = a;
}
}
class ClassC {
public b: ClassB;
constructor(b: ClassB) {
this.b = b;
}
}
@Component
struct ViewA {
label: string = 'ViewA';
@ObjectLink a: ClassA;
build() {
Row() {
Column({space:10}) {
Text(`[${this.label}] this.a.value = ${this.a.value}`)
.fontSize(20)
Button(`ViewA: this.a.value add 1`)
.backgroundColor('#ff7fcf58')
.onClick(() => {
this.a.value += 1
console.log('this.a.value:' + this.a.value)
})
}
.width("100%")
}
}
}
@Entry
@Component
struct ViewB {
@State child: ClassC = new ClassC(new ClassB(new ClassA(10)));
build() {
Column({space:10}) {
ViewA({ a:this.child.b.a })
Text(`ViewB:${this.child.b.a.value}`)
Button(`ViewB: this.c.b.a.value add 10`)
.backgroundColor('#ff7fcf58')
.onClick(() => {
this.child.b.a.value += 10
console.log('this.child.b.a.value:' + this.child.b.a.value)
})
}
}
}
多层嵌套都要嵌套都需要加@Observed,ClassB和ClassC都加上试试