鸿蒙学习记录

创建了一个名为 MyButton 的自定义组件,它显示了按钮的点击次数,并在每次点击时增加计数。

@Component struct MyButton { @State count: number = 1 build() { Row() { Text('点击次数:' + this.count.toString()) Button('点击我').onClick(() => { this.count++ }) } .justifyContent(FlexAlign.SpaceBetween) .padding(10) .border({ width: 1 }) .width('100%') } } @Entry @Component struct Index { build() { Column() { MyButton() MyButton({ count: 10 }) MyButton() } .padding(20) } }

传递参数

@Component struct MyFoodComponent { @State food: string = 'AAAA' dog: string = 'BBBB' // 普通变量也是响应式的 sayHello = () => { console.log('默认的打招呼') } build() { Row() { Text(`自定义组件 {this.dog} 喜欢吃 {this.food}`) Button('点击按钮') .onClick(() => { this.food += '!' this.dog += '.' this.sayHello() }) } .border({ width: 1 }) .padding(20) } } @Entry @Component struct Index { build() { Column() { MyFoodComponent() MyFoodComponent({ dog: 'CC', food: 'DD', sayHello() { console.log('外部传入的打招呼的逻辑') } }) .border({ width: 1 }) .padding(20) MyFoodComponent() } .padding(20) } }

事件处理和回调

@Component struct CardComponent { title: string = '' subTitle: string = '' clickHandler = () => { AlertDialog.show({ message: '默认的功能' }) } build() { Column() { Row() { Text(this.title).layoutWeight(1) Row() { Text(this.subTitle) Image($r('app.media.ic_public_arrow_right')) .width(20) } .onClick(() => { this.clickHandler() }) } Row() { Text('默认的内容') } .height(100) } .backgroundColor(Color.Pink) .borderRadius(10) .padding(10) .margin({ bottom: 20 }) } } @Entry @Component struct Index { build() { Column() { CardComponent({ title: '所有评论', subTitle: '查看更多', clickHandler() { AlertDialog.show({ message: '查看更多评论' }) } }) CardComponent({ title: '所有商品(100+)', subTitle: '查看更多', clickHandler() { AlertDialog.show({ message: '查看更多商品' }) } }) } .padding(20) } }

相关推荐
Risehuxyc2 小时前
PHP中如何将字符串转成字节数组,再异或成一个字节
开发语言·php
饮水桶_T2 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
悠仁さん2 小时前
【C++】unordered_map_set 模拟实现
开发语言·c++
1-1=03 小时前
Vue 全局事件总线
前端·javascript·vue.js
唐老板3 小时前
前端和后端,转 AI 全栈怎么转
前端·后端
AI前端工程狮4 小时前
我给 MCP 工具加了删除确认,用户点了拒绝,数据还是删了
javascript·人工智能·程序员
用户298698530144 小时前
在 React 中实现 Excel 文本与数字互转的完整实践
javascript·react.js·excel
Risehuxyc4 小时前
为什么php结束符?>省略不写
开发语言·php
程序员鱼皮4 小时前
Antigravity 保姆级实战教程,从 0 到 1 万字干货!
前端·后端·ai编程
徐小夕4 小时前
JitKnow AI知识库:把任何文档,一键变成可访问和可配置的Wiki站点
前端·vue.js·github