#鸿蒙通关秘籍#在使用@ObjectLink时怎样保证数据的双向同步?

HarmonyOS
2024-12-04 13:59:01
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
EDIF梦织星

保证@ObjectLink变量与数据源的双向同步,需遵循以下步骤:

  1. 确保@ObjectLink装饰的变量指向的是@Observed装饰类的实例。
  2. 变量必须是从父组件传递过来的@State@Link@Provide等装饰型变量中的元素。
  3. 切勿为@ObjectLink变量重新赋值,以免破坏同步关系。
@Entry
@Component
struct ParentComponent {
  @State items: ClassA[] = [new ClassA(0), new ClassA(1)];

  build() {
    ChildComponent({ item: this.items[0] }) // @ObjectLink同步
  }
}

@Component
struct ChildComponent {
  @ObjectLink item: ClassA;

  build() {
    Button('Update Value').onClick(() => {
      this.item.value += 1; // 属性变化同步到ParentComponent
    })
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

上述示例中,保证了通过@ObjectLink的数据同步。

分享
微博
QQ
微信
回复
2024-12-04 15:27:21
相关问题
数组列表如何实现数据双向同步
1047浏览 • 1回复 待解决