#鸿蒙通关秘籍#如何通过@Provide和@Consume装饰器在HarmonyOS中实现跨层级的组件通信?

HarmonyOS
2024-11-27 13:00:04
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
hm673ff0f23aa91

@Provide装饰器在祖先组件中定义状态,@Consume装饰器在后代组件中使用此状态以实现跨层级通信。示例如下:

// 祖先组件
@Component
struct AncestorComponent {
  @Provide sharedResource: string = 'shared value'

  build() {
    IntermediateComponent()
  }
}

// 中间组件
@Component
export struct IntermediateComponent {
  build() {
    DescendantComponent()
  }
}

// 后代组件
@Component
export struct DescendantComponent {
  @Consume sharedResource: string

  build() {
    Text(this.sharedResource)
      .onClick(() => {
        this.sharedResource = 'Modified by Descendant'
      })
  }
}
  • 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.
  • 27.
  • 28.
  • 29.
  • 30.
分享
微博
QQ
微信
回复
2024-11-27 14:00:09
相关问题