HarmonyOS 鸿蒙Next:如何根据配置字符串去调用方法

HarmonyOS 鸿蒙Next:如何根据配置字符串去调用方法 在LIst内, item点击时, 想要根据item配置的方法名(字符串), 去调用对应的function,这个有相关的demo或者示例么

想要实现如下示例:

storage() {
  console.log('aaaa')
}

例如 cell.action = ‘storage’, 可以直接调用到storage() 这个方法

let func = new Function(`${cell.action}`);

func()
3 回复

可以使用 Record<string, Function> 的方式实现

定义时:

export class dddd {
  fun : Record<string, Function> = {};

  constructor() {
    this.fun={'ssss':this.ddd1,'sdss':this.ccc}
  }
  ddd1(){
    console.log('ddd1')
  }
  ccc(){
    console.log('cccc')
  }
}

调用时:
import display from '@ohos.display';
import { dddd } from './FunTest';

@Component
struct DisplayTest {
  private ddd : dddd = new dddd()
  build() {
    Column({space:20}){
      Button('Test')
        .type(ButtonType.Capsule)
        .onClick(() => {
          this.ddd.fun['ssss']()
          this.ddd.fun['sdss']()
        })
        .width('50%')
    }
    .width("100%")
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

更多关于HarmonyOS 鸿蒙Next:如何根据配置字符串去调用方法的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


不支持动态执行,只能if … if … if …

在HarmonyOS(鸿蒙)系统中,根据配置字符串调用方法通常涉及反射机制或特定的配置解析框架。虽然鸿蒙系统有其独特的API和框架,但基本思想与其他现代操作系统类似。以下是如何根据配置字符串调用方法的简要说明:

  1. 配置解析:首先,你需要解析配置字符串,这通常是一个包含方法名及其参数的JSON或其他格式的字符串。解析后,你将获得方法名和参数列表。

  2. 方法查找:利用鸿蒙提供的反射机制(如果有)或特定的API,根据类名和方法名查找对应的方法。在鸿蒙中,这可能涉及使用特定的类或接口来实现。

  3. 参数匹配与调用:将解析得到的参数与找到的方法参数进行匹配,确保类型一致。然后,调用该方法并传入匹配的参数。

  4. 错误处理:在解析、查找和调用过程中,需要添加适当的错误处理逻辑,以应对可能的异常情况,如方法不存在、参数类型不匹配等。

请注意,鸿蒙系统的具体实现细节可能与其他操作系统有所不同,因此上述步骤需要根据鸿蒙系统的API文档进行具体实现。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部