鸿蒙:配置事件

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

(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 小时前
纯脚本项目的跨平台适配方法论:getoptions在开源鸿蒙PC平台的实现解析
华为·开源·harmonyos
搬砖的kk4 小时前
基于Flutter开发应用如何快速适配HarmonyOS
flutter·华为·harmonyos
码灵4 小时前
鸿蒙(HarmonyOS)开发板是否能够运行 Java 应用?
harmonyos
音浪豆豆_Rachel6 小时前
Flutter 与原生通信的桥梁:深入解析 Pigeon 与后台线程通信
flutter·harmonyos
音浪豆豆_Rachel7 小时前
Flutter跨平台通信的智能配置:Pigeon注解配置与鸿蒙生态深度集成
flutter·华为·harmonyos
FrameNotWork10 小时前
HarmonyOS 教学实战(六):复杂表单与校验体系(把“最难写”的模块写优雅)
华为·harmonyos
HMS Core11 小时前
【FAQ】HarmonyOS SDK 闭源开放能力 — Form Kit
华为·harmonyos
IT充电站12 小时前
鸿蒙应用开发之鸿蒙沙箱文件如何存媒体库?
harmonyos
IT充电站12 小时前
鸿蒙应用开发之通过AVPlayer如何实现音乐播放、暂停、音量设置?
harmonyos
HMS Core12 小时前
【FAQ】HarmonyOS SDK 闭源开放能力 — Share Kit
华为·harmonyos