鸿蒙:配置事件

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

(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)
相关推荐
花椒技术2 小时前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
一维Ace10 小时前
HarmonyOS ArkTS 按钮组件全解:Button、Toggle 状态交互实战
harmonyos
anyup1 天前
来简单聊聊鸿蒙开发,万元奖金的事~
前端·华为·harmonyos
Georgewu1 天前
【无测试机别害怕】华为云鸿蒙云手机南:从零到联调全流程详解
harmonyos
Georgewu2 天前
【HarmonyOS 7】DevEco Code安装与使用
harmonyos
Georgewu2 天前
【HarmonyOS 7】鸿蒙应用开发如何屏蔽剪切板
harmonyos
谷子在生长3 天前
纯血鸿蒙自定义弹窗最佳实践:从「到处复制」到「一行调用」
前端·harmonyos
小魔女千千鱼3 天前
把 Go 塞进鸿蒙PC:windows上用 c-shared 跑 2048
harmonyos
TrisighT3 天前
Electron 跑在鸿蒙 PC 上,单窗口和多窗口内存差 800MB?我抓了 5 组数据
性能优化·electron·harmonyos