鸿蒙:配置事件

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

(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)
相关推荐
星释1 小时前
鸿蒙Flutter三方库适配指南:09.版本升级适配
flutter·华为·harmonyos
CN-cheng14 小时前
Flutter项目在HarmonyOS(鸿蒙)运行报错问题总结
flutter·华为·harmonyos·flutter运行到鸿蒙
平平不平凡14 小时前
鸿蒙音频播放器深度解析:从核心设计到完整实现
harmonyos
HMSCore17 小时前
【FAQ】HarmonyOS SDK 闭源开放能力 — Form Kit
harmonyos
爱笑的眼睛111 天前
HarmonyOS数据存储Kit深度实践:从架构设计到性能优化
华为·harmonyos
爱笑的眼睛111 天前
HarmonyOS后台代理提醒Agent:构建智能提醒功能的深度解析
华为·harmonyos
爱笑的眼睛111 天前
ArkTS可选链与空值合并:提升HarmonyOS应用开发的安全性与简洁性
华为·harmonyos
星释1 天前
鸿蒙Flutter三方库适配指南:11.插件发布上线及使用
flutter·华为·harmonyos
奔跑的露西ly1 天前
【HarmonyOS NEXT】常见的性能优化
华为·性能优化·harmonyos
hashiqimiya1 天前
harmonyos的鸿蒙的跳转页面的部署参数传递
华为·harmonyos