#鸿蒙通关秘籍#如何使用@Provide和@Consume实现ArkTS中的跨层级参数传递?

HarmonyOS
2024-11-26 15:55:07
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
hm673ff09671132

在ArkTS中,@Provide和@Consume装饰器允许在父组件和子组件之间跨多层级传递数据:

// 父组件
@Entry
@Component
struct Parent {
  @Provide('weight') weight: number = 50

  build() {
    Column({ space: 20 }) {
      Text(`父组件体重值:${this.weight}`)
      Button(`父组件体重+1`).onClick(() => {
        this.weight++
      })
      Child()
    }.padding(20).alignItems(HorizontalAlign.Start)
  }
}

// 子组件
@Component
struct Child {
  build() {
    Grandson()
  }
}

// 孙组件
@Component
struct Grandson {
  @Consume('weight') weight: number

  build() {
    Column({ space: 20 }) {
      Text(`孙组件体重值:${this.weight}`)
      Button(`孙组件体重+1`).onClick(() => {
        this.weight++
      })
    }.margin({ top: 50 })
  }
}
  • 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.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
分享
微博
QQ
微信
回复
2024-11-26 16:55:08


相关问题