【鸿蒙应用ArkTS开发系列】- 父组件直接调用子组件方法

今天这篇文档,讲的是鸿蒙应用开发中会遇到的一种常见场景,父组件显式调用子组件的方法

最近很多同学反馈,在鸿蒙ArkTS 应用开发过程中,在对页面的页面层级进行梳理,抽取子组件的时候,由于一些原先写在页面Page中的方法会定义到子组件component中去,但是有些场景需要在父组件中调用子组件的方法。

有些同学可能会考虑使用事件来进行处理,但是对于一些同步调用的场景,比如调用子组件的一个方法,然后同步返回一个数据,这种场景使用事件,无法实现,如果使用事件,定义双向事件接收数据,会使代码的可读性变差,也会使代码功能变得复杂。

下面介绍一种官方提供的父组件显式调用子组件的方法(官方文档中有提到,很多同学可能没有留意到)

**

1. 创建子组件ChildComponent

**

import { ChildComponentController } from './ChildComponentController';
@Component
export struct ChildComponent {
  @State message: string = 'Hello World From ChildComponent'
  public mCmpController: ChildComponentController = null;

  aboutToAppear() {
    if (this.mCmpController) {
      this.mCmpController.attach(this); //绑定控制器
    }
  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
    .backgroundColor(Color.Blue)
  }

  getName(): string {
    return 'my name is ChildComponent!';
  }
}

这里子组件ChildComponent 提供一个getName的方法提供父组件调用。

**

接下来我们为ChildComponent 创建组件控制器ChildComponentController

2. 创建组件控制器ChildComponentController

**

import { ChildComponent } from './ChildComponent';

export class ChildComponentController {
  private mComponent: ChildComponent = null;

  attach(component: ChildComponent) {
    this.mComponent = component;
  }

  public getName(): string {
    if (this.mComponent) {
      return this.mComponent.getName();
    }
    return '';
  }
}

子组件控制器提供了一个attach方法,通过该方法将其与组件进行绑定(实际上就是持有组件实例),通过上面代码我们知道,在子组件ChildComponent的aboutToAppear函数中,我们进行了attach的调用,那子组件需要一个控制器实例,这个控制器实例从哪里获取呢,其实就是父组件引用子组件的时候设置的。

子组件除了attach方法外,我们还看到了一个getName方法,这个方法只是一个代理方法,具体实现是在子组件中完成。

**
最后 在ParentComponent 创建ChildComponentController实例,使用控制器显式调用子组件的方法

3. 创建ChildComponentController实例,调用子组件的方法

**

import { ChildComponent } from './ChildComponent'
import { ChildComponentController } from './ChildComponentController';

@Component
export struct ParentComponent {
  @State message: string = ''
  private mChildComponentController: ChildComponentController = new ChildComponentController();

  build() {
    Row() {
      Column() {

        Column() {
          Text('ParentComponent')
            .fontSize(25)
            .fontWeight(FontWeight.Bold)
            
          Button("调用子组件方法")
            .width("80%")
            .height("50vp")
            .margin({ top: "10vp", bottom: '10vp' })
            .onClick(() => {
              this.message = this.mChildComponentController.getName();
            })
            
          Text(this.message)
            .fontSize(25)
        }
        .height('50%')
        .justifyContent(FlexAlign.Center)

        ChildComponent({ mCmpController: this.mChildComponentController })
          .height('50%')
      }
      .width('100%')
    }
    .height('100%')
  }
}

父组件ParentComponent 在build方法中引用ChildComponent的时候,
ChildComponent({ mCmpController: this.mChildComponentController })
将创建的ChildComponentController 设置到子组件中。子组件创建的时候将自身实例通过ChildComponentController 的attach进行绑定,父组件通过ChildComponentController 调用子组件的getName方法。

代码简简单单,希望能够解决同学们在实际开发中遇到的问题。

在这里插入图片描述

### 鸿蒙系统中父组件调用子组件方法的实现 在鸿蒙系统的开发环境中,为了使父组件能够调用子组件中的特定功能或属性,通常采用事件回调机制或是通过定义接口的方式来进行交互。下面介绍一种基于 `AbilitySlice` 和自定义控件之间通信的方法[^1]。 对于这种场景下的具体实践: #### 定义公共接口 首先,在项目里创建一个新的 Java 文件来声明一个公共接口,该接口用于规定哪些操作可以被外部访问。例如命名为 IChildComponentAction.java: ```java public interface IChildComponentAction { void performSpecificOperation(); } ``` #### 修改子组件类 接着修改目标子组件所在的类文件,让其继承上述所定义好的接口并重写相应的方法体。假设当前正在处理的是名为 ChildComponent 的布局,则编辑对应的 .java 或者 .kt 文件如下所示: ```java import ohos.aafwk.ability.AbilitySlice; // ... other imports ... public class ChildComponent extends AbilitySlice implements IChildComponentAction { @Override public void onStart(Intent intent) { super.onStart(intent); // Initialization code here... } @Override public void performSpecificOperation() { // Implement the logic that should be executed when this method is called from parent component. } } ``` #### 更新父级组件代码 最后一步是在负责管理整个页面结构的那个主要部分——即所谓的 "Parent Component" 中获取到实例化后的子部件对象,并利用它触发之前设置的动作。这可以通过多种途径完成,比如直接引用、依赖注入或者是借助某种形式的消息传递框架;这里给出最简单的做法作为例子说明: ```java IChildComponentAction childCompInstance; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); // Assuming 'child' refers to an instance of your custom view or another ability slice you want to interact with. childCompInstance = (IChildComponentAction)getAbility().getAbilityContext().findAbilitySlice(ChildComponent.class.getName()); } void someMethodInParent(){ if(childCompInstance != null){ childCompInstance.performSpecificOperation(); }else{ Log.error("Failed to get reference to child component."); } } ``` 以上就是关于如何实现在鸿蒙操作系统下由父级组件向子级发起请求的一种常见模式[^2]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值