鸿蒙:配置事件

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

(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)
相关推荐
用户0934077735144 分钟前
HarmonyOS WPS Open SDK 二开答疑:ToB/ToC 差异与接入误区
harmonyos
心中有国也有家8 分钟前
AtomGit Flutter 鸿蒙客户端: AnimatedScale 与 AnimatedContainer 联合实战
android·javascript·flutter·华为·harmonyos
风华圆舞14 分钟前
鸿蒙HarmonyOS矩阵加载动效实战 —— 从「假旋转」到可复用的波前反馈组件
华为·矩阵·harmonyos·arkui·gradientspin·波前动效·oklab
2301_7681034922 分钟前
HarmonyOS宠物邻里实战第16篇:寄养申请状态机、记录时间线与回归测试
mongodb·集成测试·express·harmonyos·状态机
不羁的木木1 小时前
HarmonyOS APP实战-画图APP - 第6篇:形状切换与UI优化
ui·华为·harmonyos
xd1855785551 小时前
鸿蒙PC平台Flutter魔术教学应用开发实践:打造跨端沉浸式魔术学习体验
人工智能·学习·flutter·华为·harmonyos·鸿蒙
●VON1 小时前
HarmonyKit | 移动端开发者工具类应用的现状与趋势
git·华为·性能优化·harmonyos·鸿蒙
不羁的木木1 小时前
HarmonyOS APP实战-画图APP - 第10篇:色彩管理功能
华为·harmonyos
●VON1 小时前
HarmonyKit | 鸿蒙开发协作:如何为 HarmonyKit 贡献一个新的工具
git·华为·harmonyos·鸿蒙
2301_768103491 小时前
HarmonyOS趣味相机实战第1篇:工程结构、相机权限申请与真实拍摄主流程
harmonyos·arkts·项目实战·水印相机·camerakit