鸿蒙:配置事件

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

(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)
相关推荐
lqj_本人19 分钟前
鸿蒙Qt网络通信:HTTPS握手失败与证书陷阱
qt·https·harmonyos
lqj_本人7 小时前
HarmonyOS + Cordova 工程搭建与目录结构:从零到跑通 & 常见报错排查
华为·harmonyos
Georgewu8 小时前
【HarmonyOS 6】在UI控件上滑动也会触发onClick点击事件?
harmonyos
Georgewu9 小时前
【HarmonyOS 6】为什么getContext 废弃,使用getHostContext说明
harmonyos
爱笑的眼睛119 小时前
HarmonyOS应用崩溃捕获与上报:分布式场景下的深度实践与优化
华为·harmonyos
A懿轩A10 小时前
【2025版 OpenHarmony】GitCode 口袋工具 v1.0.1 更新发布:Flutter + HarmonyOS 封装导航栏进行跳转
flutter·harmonyos·openharmony·gitcode·开源鸿蒙
不羁的木木13 小时前
【开源鸿蒙跨平台开发学习笔记】Day01:React Native 开发 HarmonyOS-环境搭建篇
学习·开源·harmonyos
lqj_本人13 小时前
鸿蒙与Qt的双线程模型:主线程与UI线程的博弈
qt·ui·harmonyos
御承扬14 小时前
鸿蒙原生系列之拖拽事件
华为·harmonyos·拖拽事件·ndk ui
不爱吃糖的程序媛14 小时前
开源鸿蒙 Cordova 设备信息插件开发详解
华为·开源·harmonyos