本文原创发布在华为开发者社区

介绍

本示例主要讲解组件间通信方式,包含以下几种场景:

  1. 父子组件单向通信
  2. 父子组件双向通信
  3. 前后代组件双向同步
  4. 组件嵌套类双向同步

实现组件间通信源码链接

效果预览

请添加链接描述

使用说明

进入应用,点击按钮可浏览不同组件关系之间的效果。

实现思路

父子组件单向通信

单向通信时,修改子组件的值,父组件不会同步修改,通过单独设置父组件的属性实现,点击按钮时只改变子组件的属性,父组件与原来一致。核心代码如下,源码参考ParentChildOneWay.ets

Column({ space: 10 }) {
        Text(`展示当前组件(简单类型 1行):${this.simple}`)
        Text(`展示当前组件(嵌套类型)2-3行:${this.nestObj.name}   ${this.nestObj.obj.name}`)
        Image(this.img).width(100)
        Button('修改当前组件值', { stateEffect: true, type: ButtonType.Capsule }).onClick(() => {
          this.simple = 'my name is:Jack11'
          this.nestObj.name = 'Jack22'
          this.nestObj.obj.name = 'Jack33'; // 嵌套类型的属性修改不生效
          this.img = $rawfile('2.PNG')
        })
        ChildOneWay({
          simple: this.simple,
          nest: this.nestObj,
          img: this.img,
          nest_1: this.nestObj.obj
        })
      }

父子组件双向通信

双向通信时,修改子组件的值,父组件同步修改,通过一起设置父子组件的属性实现,父子组件使用同样的属性,点击按钮时一起改变。核心代码如下,源码参考ParentChildBidirectional.ets

 Column() {
        Text(`展示当前组件(简单类型 1行):${this.simple}`)
        Text(`展示当前组件(嵌套类型)2-3行:${this.nestObj.name}   ${this.nestObj.obj.name}`)
        Image(this.img).width(100)
        Button('修改当前组件值', { stateEffect: true, type: ButtonType.Capsule }).onClick(() => {
          this.simple = 'my name is:Jack11'
          this.nestObj.name = 'Jack22'
          this.nestObj.obj.name = 'Jack33'; // 嵌套类型的属性修改不生效
          this.img = $rawfile('2.PNG')
        })
        ChildBidirectional({
          simple: this.simple,
          nest: this.nestObj,
          img: this.img
        })
      }

组件嵌套类双向同步

点击“修改当前组件值”按钮,通过修改inestObj1Arr 和nestObj2Arr的值,嵌套子组件与父组件同步变化。核心代码如下,源码参考
NestedBidirectionalPage.ets

Column() {
        Text(`展示当前组件(简单类型 1行):${this.nestObj1Arr[0].name}`)
        Text(`展示当前组件(嵌套类型)2行: ${this.nestObj1Arr[0].obj.name}`)

        Text(`展示ObjectLink数据长度 5行: ${this.nestObj1Arr.length}`)

        Text(`展示当前组件(简单类型 3行):${this.nestObj2Arr[0].name}`)
        Text(`展示当前组件(嵌套类型)4行: ${this.nestObj2Arr[0].obj.name}`)

        Text(`展示ObjectLink数据长度 5行: ${this.nestObj2Arr.length}`)

        Button('修改当前组件数据', { stateEffect: true, type: ButtonType.Capsule }).onClick(() => {
          this.nestObj1Arr = [NestObj_1.instance('Jack11', new TwoNestObj_1('Jack22'))]
          this.nestObj2Arr = [NestObj_2.instance('Jack33', new TwoNestObj_2('Jack44'))]
        })

        NestedBidirectional({
          nestObj1Arr: this.nestObj1Arr,
          nestObj2Arr: this.nestObj2Arr
        })
      }

鸿蒙场景化代码
1 声望0 粉丝