鸿蒙:配置事件

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

(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)
相关推荐
●VON几秒前
AtomGit Flutter鸿蒙客户端:文件树与代码浏览
android·服务器·安全·flutter·harmonyos·鸿蒙
molong9317 小时前
鸿蒙基础之数据api全解析
华为·harmonyos
李二。8 小时前
鸿蒙原生ArkTS-鸿蒙6.0新特性-动态模糊视频背景登录页
华为·音视频·harmonyos
李二。10 小时前
鸿蒙原生ArkTS-鸿蒙6.0新特性-粒子特效壁纸动态桌面
华为·harmonyos
科技与数码11 小时前
鸿蒙智能待办:钉钉学而思待办自动同步日历
华为·钉钉·harmonyos
不爱学英文的码字机器13 小时前
[鸿蒙PC命令行移植适配]移植rust三方库tokei到鸿蒙PC的完整实践
华为·rust·harmonyos
EterNity_TiMe_13 小时前
[鸿蒙PC命令行移植适配]移植rust三方库ouch到鸿蒙PC的完整实践
华为·rust·harmonyos
提子拌饭13313 小时前
路径动画用鸿蒙PC用Electron框架实现流动效果技术详解
华为·electron·开源·harmonyos·鸿蒙
李二。14 小时前
鸿蒙原生ArkTS通讯录管家实战开发详解
华为·harmonyos
EterNity_TiMe_14 小时前
[鸿蒙PC命令行移植适配]移植rust三方库broot到鸿蒙PC的完整实践
华为·rust·harmonyos