鸿蒙开发笔记-@Link父子双向同步传递数据

一、概述

使用 @Link 可以实现父组件和子组件的数据双向同步。

二、使用步骤

  1. 将父组件的状态属性传递给子组件;
  2. 子组件变量通过 @Link 修饰即可;

三、talk is cheap, show me the code

子组件代码

@Component
struct SonComponent {
  //@Link双向同步
  @Link count: number

  build() {
    Column() {
      Text('子组件')
      Text(this.count.toString())
      Button('子组件修改count')
        .onClick(() => {
          this.count += 2
        })
    }
    .backgroundColor(Color.Brown)
    .height(200)
    .width(200)
  }
}

父组件代码

@Component
struct Index {
  @State count: number = 1

  build() {
    Column() {
      Text('父组件')
      Text(this.count.toString())
      Button('父组件修改count')
        .onClick(() => {
          this.count++
        })

      //使用子组件
      SonComponent({
        count: this.count
      })
        .margin({ top: 50 })
    }
    .backgroundColor('#F1F3F5')
    .height('100%')
    .width('100%')
  }
}

示意图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>