父组件修改子组件能刷新,子组件修改父组件没反应?

帮朋友提问:

父组件修改子组件能刷新,子组件修改父组件没反应,那个大佬能帮我看看是不是我代码有问题,还是文档有问题?
@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)
    })
}

}
}

阅读 326
1 个回答

多层嵌套都要嵌套都需要加@Observed,ClassB和ClassC都加上试试

@Observed
class ClassB {
public a: ClassA;

constructor(a: ClassA) {

this.a = a;
}
}
@Observed
class ClassC {
public b: ClassB;

constructor(b: ClassB) {

this.b = b;
}
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题