鸿蒙:配置事件

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

(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)
相关推荐
颜颜yan_4 小时前
Eclipse Theia 鸿蒙 PC 适配全记录:在 HarmonyOS PC 上运行完整 IDE 工作台
ide·eclipse·harmonyos
鸽芷咕4 小时前
Mu Editor 鸿蒙 PC 适配全记录:用 Qt 与嵌入式 CPython 重建教学型 Python IDE
python·qt·harmonyos
鸽芷咕4 小时前
MongoDB 鸿蒙 PC 适配全记录:从 Bazel 交叉编译到 HNP 原生数据库服务
数据库·mongodb·harmonyos
安好说AI4 小时前
Flutter for OpenHarmony 实战:媒体选择库 adaptive_image_picker 的鸿蒙化适配全解读
flutter·harmonyos·媒体
贾伟康5 小时前
【HarmonyOS 7新能力|011】分布式数字身份入门实战:从能力边界到最小可运行链路
harmonyos·arkts·隐私保护·数字身份·harmonyos 7
颜颜yan_5 小时前
Geany 鸿蒙 PC 适配全记录:以 Qt 重建轻量 IDE,打通编辑、项目检索与命令执行
ide·qt·harmonyos
●VON5 小时前
Flutter 鸿蒙插件适配实战:用 app_version_details 1.0.3 读取版本号与包名
flutter·华为·harmonyos
承渊政道5 小时前
PR-Agent鸿蒙PC适配全记录:从Python服务端代理到ArkTS原生评审客户端
python·华为·代理模式·agent·harmonyos·pc端
网络豆5 小时前
Apache Hive 鸿蒙 PC 适配全记录:以 Qt 客户端打通 HiveQL、监控与元数据访问
hive·apache·harmonyos
网络豆6 小时前
Apache HBase 鸿蒙 PC 适配全记录:用 Qt 原生客户端打通 REST 管理与数据读写
apache·hbase·harmonyos