HarmonyOS 回调函数的写法?

目前写回调函数有几种方法。

阅读 582
1 个回答

可参考如下写法:

interface MyCallback {
  func_1(id: string) : void;
  func_2(id: string, text: string): void;
  func_3(id: string): void;
}

如果想要实现里面接口可以将参数设置为回调函数。

interface MyCallback {
  func_1: (id: string) => void;
  func_2: (id: string, text: string) => void;
  func_3: (id: string) => void;
}

let a: MyCallback = {
  func_1: (id: string) => {},
  func_2: (id: string,text:string) => {},
  func_3: (id: string) => {}
}

具体调用参考Demo如下:

export interface MyInterDemo {
  func_1: () => void;
  func_2: () => boolean;
  func_3: (arg: string) => void;
}

@Entry
@Component
struct TestInterfacePage {

  testInter(inter: MyInterDemo) {
    console.log('testInter');
    inter.func_1();
    inter.func_2();
    inter.func_3('hello');
  }

  build() {
    Row() {
      Column() {
        Button('Test interface')
          .onClick(() => {
            let demo: MyInterDemo = {
              func_1: () => {
                console.log('func_1');
              },
              func_2: () => {
                console.log('func_2');
                return true;
              },
              func_3: (arg: string) => {
                console.log('func_3:' + arg);
              }
            }
            this.testInter(demo);
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进