鸿蒙:配置事件

事件方法以"."链式调用的方式配置系统组件支持的事件,建议每个事件方法单独写一行。

(1)使用箭头函数配置组件的事件方法。

TypeScript 复制代码
Button('Click me')
  .onClick(() => {
    this.myText = 'ArkUI';
  })

(2)使用匿名函数表达式配置组件的事件方法,要求使用bind,以确保函数体中的this指向当前组件。

TypeScript 复制代码
Button('add counter')
  .onClick(function(){
    this.counter += 2;
  }.bind(this))

(3)使用组件的成员函数配置组件的事件方法。

TypeScript 复制代码
myClickHandler(): void {
  this.counter += 2;
}
...
Button('add counter')
  .onClick(this.myClickHandler.bind(this))

(4)使用声明的箭头函数,可以直接调用,不需要bind this

TypeScript 复制代码
fn = () => {
  console.info(`counter: ${this.counter}`)
  this.counter++
}
...
Button('add counter')
  .onClick(this.fn)
相关推荐
天聚数行3 小时前
华为鸿蒙系统(HarmonyOS)调用天聚数行 API 教程
华为·php·harmonyos·tianapi·天聚数行
BlackWolfSky5 小时前
鸿蒙加解密
华为·harmonyos
融云5 小时前
融云 4 款 SDK 首批通过 GIIC 鸿蒙生态评测
华为·harmonyos
讯方洋哥5 小时前
HarmonyOS应用开发—页面路由
华为·harmonyos
鸿蒙开发工程师—阿辉5 小时前
HarmonyOS 5 高效使用命令:HDC 基本使用
华为·harmonyos
梧桐ty6 小时前
鸿蒙 + Flutter:构建万物互联时代的跨平台应用新范式
flutter·华为·harmonyos
梧桐ty8 小时前
鸿蒙 + Flutter:破解“多端适配”困局,打造万物互联时代的高效开发范式
flutter·华为·harmonyos
Python私教8 小时前
鸿蒙应用的测试和调试完全指南:从单元测试到性能分析
华为·单元测试·harmonyos
Archilect8 小时前
终点、光圈与 Lottie 生命周期:复杂关闭动效的「收尾工程」
harmonyos
鸿蒙开发工程师—阿辉8 小时前
HarmonyOS 5 高效使用命令:HDC 使用指南
华为·harmonyos