HarmonyOS 父子组件数据通信(Prop与Link)

我们可以先写一个这样的小案例

typescript 复制代码
@Entry
@Component
struct Index {

  @State name:string = "小猫猫";

  build() {
    Row() {
      Column() {
        Text(this.name)
        Button("改个name").onClick(() => {
          this.name = this.name == "小猫猫"?"小狗狗":"小猫猫";
        })
        son()
        son({const: this.name })
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Component
struct son {
  const:string = "你好"
  build() {
    Row() {
      Column() {
        Text(this.const)
      }
    }
  }
}

这里 我们定义了一个子组件 son 里面写了一个变量 const 字符串类型 默认值为"你好"

然后 用Text文本组件展示内容

然后 我们父组件调用子组件 一个传入了const 一个没传

运行结果如下

然后 我们点击父组件的button name是会发生改变的 从小猫猫变成小狗狗

我们点击按钮

但是 我们明显发现 我们传给子组件的 const 没有因为父组件的name改变而改变

我们可以给他加一个注解

将代码改成这样

typescript 复制代码
@Entry
@Component
struct Index {

  @State name:string = "小猫猫";

  build() {
    Row() {
      Column() {
        Text(this.name)
        Button("改个name").onClick(() => {
          this.name = this.name == "小猫猫"?"小狗狗":"小猫猫";
        })
        son({const: this.name })
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Component
struct son {
  @Prop const:string
  build() {
    Row() {
      Column() {
        Text(this.const)
      }
    }
  }
}

这里 我们给子组件的 const 修饰上 Prop

首先需要强调 Prop 修饰的变量不能有默认值 你写了默认值会报错 必须从父组件传进来

此时 我们点击button按钮 Prop 修饰的变量会根据父组件的传递内容变化而变化

但这种传递是单向的 我们修改子组件的 const 父组件不会受影响 而且不要在子组件中乱动父组件传的值 你在子组件改父组件传的东西 是有问题的

然后 我们还有一种数据修饰 link

我们将代码改成这样

typescript 复制代码
@Entry
@Component
struct Index {

  @State name:string = "小猫猫";

  build() {
    Row() {
      Column() {
        Text(this.name)
        Button("改个name").onClick(() => {
          this.name = this.name == "小猫猫"?"小狗狗":"小猫猫";
        })
        son({const: $name })
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Component
struct son {
  @Link const:string
  build() {
    Row() {
      Column() {
        Text(this.const)
        Button("改个name").onClick(() => {
          this.const = "小海豚";
        })
      }
    }
  }
}

这里 我们子组件的const变量注释换成 Link 它和Prop一样 放上去 变量就不能有默认值

然后 我们父组件传值是 如果 你是 this.变量名是会报错的

Link修饰的变量 只需要 $后面放一个组件变量就够了

然后 点击子组件button 就会修改link修饰的数据

也可以简单理解为

Prop 子集不能修改数据 父级改了 子集会响应

Link 子集和父级都可以修改数据 且双方都会响应

相关推荐
灰灰勇闯IT15 小时前
鸿蒙 5.0 开发入门第二篇:掌握 ArkTS 的 if 分支语句,实现条件逻辑判断
华为·harmonyos
2501_9253171315 小时前
[鸿蒙2025领航者闯关] 把小智AI装进「第二大脑」:从开箱到MCP智能体的全链路实战
人工智能·microsoft·harmonyos·鸿蒙2025领航者闯关·小智ai智能音箱·mcp开发
SmartBrain15 小时前
华为企业4A架构深度解析
华为·架构
柒儿吖15 小时前
让终端输出更美观:term_grid网格布局工具在OpenHarmony PC上的完整适配实战
harmonyos
柒儿吖16 小时前
深度实战:Rust交叉编译适配OpenHarmony PC——terminal_size完整适配案例
后端·rust·harmonyos
JohnnyDeng9416 小时前
ArkTs-线程池工具封装
线程池·arkts·鸿蒙
hh.h.16 小时前
Flutter应用嵌入鸿蒙智慧座舱数字孪生界面的实现
华为·harmonyos
白茶三许17 小时前
【江鸟中原】集光鸿蒙项目开发
pytorch·深度学习·harmonyos
zhujian8263717 小时前
二十一、【鸿蒙 NEXT】分词和汉字转拼音
华为·harmonyos·分词·汉字转拼音·分词ui卡顿
深海的鲸同学 luvi18 小时前
在鸿蒙设备上,如何启动一个真正可用的本地 Web 服务
华为·harmonyos