鸿蒙:配置事件

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

(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)
相关推荐
贾伟康15 小时前
【天体运行模拟|12】HarmonyOS ArkTS 本地数据文件实战:让离线资源读取失败可见可恢复
数据恢复·harmonyos·arkts·preferences·arkdata
~远在太平洋~16 小时前
05-鸿蒙 faultlog 崩溃日志分析
华为·harmonyos
Magic-ZYJ17 小时前
HarmonyOS 文件选择与读写:DocumentViewPicker、URI、沙箱目录一次搞清
深度学习·华为·harmonyos
2501_9197490317 小时前
华为鸿蒙免费提醒APP—小羊提醒
华为·harmonyos·鸿蒙
OH_TPC17 小时前
HarmonyOS APP开发---“图迹“旅行相册App,需要用到这个库
华为·harmonyos·鸿蒙
lilian23317 小时前
HarmonyOS 7 新特性(二十四)|ModularObjectExtensionAbility 与 Taihe IPC
华为·harmonyos
tsqtsqtsq030918 小时前
鸿蒙系统应用市场更新功能详解与开发适配指南
服务器·harmonyos
Georgewu18 小时前
HarmonyOS Dev Assistant (HarmonyOS开发助手)如何打通元服务开发全流程
harmonyos
2501_9197490319 小时前
华为鸿蒙免费计算油耗APP—小羊油耗
华为·harmonyos·鸿蒙
less_1213819 小时前
HarmonyOS WPS Open SDK:OpenFileRequest 构造参数与 sendRequest 打开链路
华为·sdk·harmonyos·wps·鸿蒙开发·文档编辑