鸿蒙:配置事件

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

(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)
相关推荐
贾伟康6 小时前
【共创稿事节】WaterFlow瀑布流的列宽策略
性能优化·实战·harmonyos·arkts·arkui
●VON6 小时前
芯稿 MarkDeck:在 HarmonyOS PC 上用 Markdown 生成可编辑 PPT
华为·powerpoint·harmonyos
2601_949480066 小时前
开源鸿蒙平台 KMP 三方库「kasechange」适配全流程
华为·开源·harmonyos
马剑威(威哥爱编程)6 小时前
【HarmonyOS 7 小艺智能体实战】09:上架前先把“关”过一遍——合规自查与素材准备
人工智能·华为·harmonyos
resh_people7 小时前
开源鸿蒙平台 CMP 三方库「table」适配全流程
华为·开源·harmonyos
●VON7 小时前
芯逻辑:面向 HarmonyOS PC 的图形化编程工作台
华为·harmonyos·鸿蒙·鸿蒙pc
hhhjhl7 小时前
开源鸿蒙平台 CMP 三方库「compose-macos-26-ui」适配全流程
macos·开源·harmonyos
网络豆18 小时前
开源鸿蒙平台 CMP 三方库「navigation-compose-extended」适配全流程
华为·开源·harmonyos
2601_9494800620 小时前
开源鸿蒙平台 CMP 三方库「multiplatform-markdown-renderer」适配全流程
华为·开源·harmonyos
威哥爱编程1 天前
HarmonyOS 7 Agent 开发实战 10:降级兜底与重试
agent·harmonyos