#鸿蒙通关秘籍#使用@Observed和@ObjectLink装饰器时应该如何初始化变量?

HarmonyOS
2024-12-04 13:34:51
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
DNS寒梅傲雪

初始化使用了@ObjectLink装饰的变量时,需要从父组件传入并确保类型合规:

@Observed
class MyClass {
  public attribute: string;
  constructor(attribute: string) {
    this.attribute = attribute;
  }
}

@Entry
@Component
struct ParentComponent {
  @State instance: MyClass = new MyClass("Initial");

  build() {
    ChildComponent({ prop: this.instance }) 
  }
}

@Component
struct ChildComponent {
  @ObjectLink prop: MyClass;

  build() {
    Text(this.prop.attribute).fontSize(18)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

上面步骤确保变量被正确初始化并且能够跟踪变化。

分享
微博
QQ
微信
回复
2024-12-04 15:11:01
相关问题
如何初始化OceanBase服务环境?
4400浏览 • 1回复 待解决