鸿蒙:配置事件

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

(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)
相关推荐
OH_TPC2 分钟前
HarmonyOS APP开发---"智泊"智能停车App,需要用到这个库
harmonyos
用户1179104883334 分钟前
AI粘贴多行需求为什么会误执行?hmharness安全粘贴拆解 GitHub:swsgbl/hmharness
ai编程·harmonyos
用户09340777351434 分钟前
HarmonyOS WPS Open SDK 实践:从 HAR 集成到 OpenFileRequest 最小闭环
typescript·harmonyos
威哥爱编程7 小时前
HarmonyOS 7 Fast Kit 算法加速实战:四大核心能力,把算力从系统里"借"出来
harmonyos·arkts
威哥爱编程8 小时前
HarmonyOS 7 游戏快启实战:Graphics Accelerate Kit 内存镜像秒级启动 + 预启动,把读条变成"秒进"
harmonyos·arkts
木子雨廷8 小时前
第 19 天|Preferences:轻量缓存与状态恢复
harmonyos
威哥爱编程8 小时前
HarmonyOS 7 精准碰一碰实战:识别触碰坐标,素材精准插入指定位置
harmonyos
二流小码农8 小时前
鸿蒙开发:ArrayList,可不会让UI更新哦
android·ios·harmonyos
威哥爱编程8 小时前
HarmonyOS 7 数字盾 2.0 实战:可信数字签名、可信 UI 确认与可信输入
harmonyos
威哥爱编程8 小时前
HarmonyOS 7 数字身份 DID 实战:TEE 颁发、本人同意、最小化出示
华为·harmonyos·arkts