鸿蒙:配置事件

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

(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)
相关推荐
前端不太难10 小时前
鸿蒙 App 的“无状态 System”设计
华为·状态模式·harmonyos
UnicornDev12 小时前
【Flutter x HarmonyOS 6】魔方计时APP——计时逻辑实现
flutter·华为·harmonyos·鸿蒙·鸿蒙系统
AlbertZein1 天前
ImageKnifePro 源码解读:鸿蒙图片加载框架全貌
harmonyos
AlbertZein1 天前
鸿蒙工程化:build-profile.json5 逐字段解析
harmonyos
前端技术1 天前
鸿蒙ArkTS 自定义底部导航栏(Tabs+@Builder 极简实现)
harmonyos·鸿蒙
Swift社区1 天前
为什么“页面跳转”在鸿蒙 PC 上是错误设计?
华为·harmonyos
熬夜敲代码的小N1 天前
鸿蒙PC开发者必备!GitNext深度测评:一站式Git管理工具
git·华为·harmonyos
秋の本名1 天前
第一章 鸿蒙生态架构与开发理念
华为·wpf·harmonyos
Ww.xh1 天前
鸿蒙系统中HTML与Vue集成方案
vue.js·html·harmonyos
前端不太难1 天前
鸿蒙游戏 CI/CD:为什么你还在手动打包?
游戏·ci/cd·harmonyos