#鸿蒙通关秘籍#如何利用@Prop和@Link在ArkTS中传递和绑定子组件输入数据?

HarmonyOS
2024-11-26 16:00:03
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
NEXT 天然编程

可以通过@Prop传递初始数据,并使用@Link进行数据的双向绑定:

// 父组件
@Entry
@Component
struct Parent {
  @State city: string = '上海'

  build() {
    Column({ space: 20 }) {
      Child({ city: this.city })
      Button('定位').onClick(() => {
        this.city = '深圳'
      })
    }
  }
}

// 子组件
@Component
struct Child {
  @Prop city: string = '北京' // 默认值北京
  build() {
    Column({ space: 10 }) {
      Text(`当前所处城市:${this.city}`).fontSize(20)
    }
  }
}
  • 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-11-26 16:55:09
相关问题