【鸿蒙实战开发】组件间的数据传递

1、父传子@State和@Prop

父组件

// 导入子组件
import Child01 from '../components/Child01'

@Entry
@Component
struct StateExample {
  @State count: number = 0
  build() {
    Column() {
      Text("计数器 count:" + this.count)
      Button('count + 1').onClick(() => {
        // 这里使用 this.count++ 会有问题
        this.count += 1
      })
      Child01({ a: this.count }).margin({ top: 10 })
    }.width('100%')
    .height(300)
  }
}

子组件

@Component
export default struct Child01 {
  // 使用@Prop定义父传子数据,数据单向流动
  @Prop a: number;
  build() {
    Column() {
      Text('我是子组件Child1')
      Text('父组件传递的count:  ' + this.a)
      Button('修改父组件count数据').onClick(() => {
        this.a -= 1
      }).margin({bottom:5})
    }.width('100%').border({ width: 1, color: Color.Black })
  }
}

注意:使用@State和@Prop进行父子组件数据通信时,数据流是单向的;父组件修改count子组件可以动态更新,而子组件无法修改父组件的数据

2、父子通信@Link($state属性)

父组件

// 导入子组件
import Child02 from '../components/Child02'

@Entry
@Component
struct StateExample {
  @State count1: number = 199

  build() {
    Column() {
      Text("计数器 count1:" + this.count1)
      Button('count1 + 1').onClick(() => {
        // 这里使用 this.count++ 会有问题
        this.count1 += 1
      }).margin({ top: 5 })
      Child02({ b: $count1 }).margin({ top: 10 })
    }.width('100%')
    .height(300)
  }
}

子组件

@Component
export default struct Child02 {
  // @Link 实现父子组件的双向流动
  @Link b:number ;
  build() {
    Column({space:10}){
      Text('我是子组件Child2')
      Text('父组件传递过来的count1:  '+this
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值