鸿蒙学习记录

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

相关推荐
deli00711 分钟前
为什么最近邻路线总在绕远?2-opt 把 50 城 TSP 缩短了 20.9%
前端
CV工程师丁Sir12 分钟前
ArkWeb 手记 06|window.open 与页面跳转拦截
开发语言·php·harmonyos
夜不会漫长14 分钟前
C++:内存管理
java·开发语言·c++
guslegend16 分钟前
底层数据设计:读写分离、分库分表与热点数据隔离
前端
Southern Wind17 分钟前
AIAgent——第一章:本地 Agent 与 Vue 3 流式全栈实战
前端·javascript·vue.js
徐小黑ACG21 分钟前
Golang 基础01
开发语言·后端·golang
两万五千个小时25 分钟前
从零给 DSH 写一个 Webhook 通知插件
javascript·人工智能·架构
可乐鸡翅yeah_26 分钟前
HLS 业务 Referer‑Policy 网页元标签引发播放异常排错
前端·javascript·网络·ffmpeg·php·音视频
进击的大海贼26 分钟前
基于C#开发的久坐提醒工具
开发语言·c#
jj_ccwgw26 分钟前
从 0 到 1 搭建 pnpm + Workspaces + Turborepo Monorepo 保姆级指南
前端·node.js