鸿蒙学习记录

创建了一个名为 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) } }

相关推荐
彩虹暴龙兽5 分钟前
JavaScript 作用域、闭包与对象
javascript
锋行天下23 分钟前
LangGraph 对接 MCP 实战指南:从本地开发到线上部署与模型防坑
前端·人工智能·后端
山楂树の31 分钟前
Java 泛型:泛型类、泛型方法、泛型接口与通配符
java·开发语言·笔记
利威尔xu39 分钟前
2026-11-18-Go接口幂等设计实战
开发语言·后端·golang
Highcharts.js1 小时前
Highcharts与TypeScript集成指南
前端·javascript·typescript·前端框架·数据可视化·highcharts
跳跳的小古风1 小时前
前端转全栈:一条接口从前端请求到 SQL 完整流程
java·前端
亿元程序员2 小时前
微信小游戏备案很久?这样操作可以直接发布!
前端
福狼2 小时前
The Expanse:让风沙成为世界的一部分
前端·three.js
eggwyw2 小时前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++
桃李无言下自成蹊2 小时前
为什么越清晰的二维码越扫不出来:jsQR 四轮解码与 8 个真实坑
javascript