鸿蒙:配置事件

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

(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)
相关推荐
Archilect2 小时前
HarmonyOS ArkTS 倒计时组件实战:性能优化篇 - 从100ms刷新到流畅体验
harmonyos
Archilect2 小时前
HarmonyOS ArkTS 倒计时组件实战:高级特性篇 - 时间区间样式切换的动态配置系统
harmonyos
梧桐ty2 小时前
鸿蒙+Flutter混合工程化:构建、依赖管理与持续集成实战
flutter·华为·harmonyos
少一倍的优雅5 小时前
hi3863(WS63) 智能小车 (一) 简单介绍
单片机·嵌入式硬件·harmonyos·hi3863
卡奥斯开源社区官方6 小时前
鸿蒙智行 L3 内测启幕:从技术架构到商用落地的全链路技术拆
华为·架构·harmonyos
搬砖的kk6 小时前
Flutter UUID 鸿蒙平台适配实践 - 全版本测试与验证
flutter·华为·harmonyos
梧桐ty7 小时前
硬件交互联动:基于鸿蒙的Flutter物联网应用开发实战
flutter·华为·harmonyos
鸿蒙小白龙7 小时前
鸿蒙UniProton操作系统编译开发指导
harmonyos·鸿蒙系统·openharmony·uniproton
萌虎不虎7 小时前
【鸿蒙根据图片路径读取图片的base64数据】
华为·harmonyos
梧桐ty10 小时前
鸿蒙生态下的跨平台框架选型指南:Flutter vs React Native vs uni-app
flutter·华为·harmonyos