HarmonyOS(32) @Link标签使用指南

前言

之前写过@Link的使用,最新的API有点变化,在此做个记录。

@Link简介

子组件中被@Link装饰的变量与其父组件中对应的数据源建立双向数据绑定。。子组件变量发生变化,父组件也会随之变化,反之亦然。

@State和@Link的同步场景

在这里插入图片描述

使用示例

如下代码:

  • Child组件定义了一个用@Link修饰的变量 count。注意@Link修饰的变量不能初始化,比如 @Link count: number=1,这种写法会报错
  • Parent组件定义了一个用@State的变量countDownStartValue
  • Child的count变量由Parent组件的countDownStartValue初始化
@Component
struct Child{
  //注意@Link修饰的变量不能初始化,比如  @Link count: number=1,这种会报错
   @Link count: number;

  build() {
    Column() {
      Text(`子组件当前数字 ${this.count}`)
      // @Prop装饰的变量不会同步给父组件
      Button(`子组件改变数字`).onClick(() => {
        this.count += 1;
      }).backgroundColor(Color.Red)
    }.margin({top:20})
  }
}

@Entry
@Component
struct Parent {
  @State countDownStartValue: number = 16;

  build() {
    Column() {
      Text(`父组件当前数字 ${this.countDownStartValue}`)
      // 父组件的数据源的修改会同步给子组件
      Button(`父组件改变数字`).onClick(() => {
        this.countDownStartValue += 1;
      })
   
      Child({ count: this.countDownStartValue }).margin({top:10})
    }.width("100%")
    .margin({top:100})
    .alignItems(HorizontalAlign.Center)
  }
}
  • 初始化页面效果如下:
    在这里插入图片描述
  • 当点击一次蓝色按钮时,Child和Parent的数字都变成17
  • 当再点击一次红色按钮时,Child和Parent都变成了18
    在这里插入图片描述

参考资料

@Link装饰器:父子双向同步
@Link入门使用

相关推荐

  1. HTML中的<img>标签使用指南

    2024-06-06 17:04:16       26 阅读
  2. HTML中的<a>标签使用指南

    2024-06-06 17:04:16       32 阅读
  3. STM32 J-LINK

    2024-06-06 17:04:16       34 阅读
  4. STM32 ST-LINK

    2024-06-06 17:04:16       78 阅读
  5. yarn link使用(npm link)

    2024-06-06 17:04:16       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-06 17:04:16       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-06 17:04:16       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-06 17:04:16       87 阅读
  4. Python语言-面向对象

    2024-06-06 17:04:16       96 阅读

热门阅读

  1. C语言经典习题17

    2024-06-06 17:04:16       30 阅读
  2. Leetcode:罗马数字转整数

    2024-06-06 17:04:16       26 阅读
  3. RabbitMQ

    RabbitMQ

    2024-06-06 17:04:16      29 阅读
  4. 【VUE】el-table表格 实现滚动到底部加载更多数据

    2024-06-06 17:04:16       32 阅读
  5. 理解接口回调及其在 RabbitMQ 中的实际运用

    2024-06-06 17:04:16       31 阅读
  6. Spark SQL数据源 - Parquet文件

    2024-06-06 17:04:16       31 阅读
  7. CCA R语言实现

    2024-06-06 17:04:16       30 阅读
  8. Ubuntu 22.04, 如何让VSCode中的cmakelist高亮显示

    2024-06-06 17:04:16       27 阅读
  9. Webpack 开发快速入门

    2024-06-06 17:04:16       33 阅读