鸿蒙学习记录

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

相关推荐
Wang's Blog3 分钟前
Java 项目实战: 交友项目 - 登录发送验证码的测试验证与经验复盘
java·开发语言·交友
u0111026757 分钟前
WebP 转成 PNG 后为什么更大?图片格式转换不等于压缩
前端·javascript·vue.js
万少8 分钟前
Qoder sonus模型 20分钟,复刻 马斯克 飞天汽车
前端·后端·算法
马优晨28 分钟前
Java中的dto是什么
java·开发语言·java中的dto是什么·java的dto是什么·dto在java中是什么
java1234_小锋30 分钟前
【技术专题】HTML5 网页技术 - HTML5 列表标签
前端·html·html5
强二小哥帅31 分钟前
Kotlin 协程复习笔记
前端
不可能片场34 分钟前
工程实践 原子替换改了 ctime 怎么修
前端·electron
暧暧内含光35 分钟前
HTTP 文件传输体系全解:从协议标头、OSS 架构到流媒体分片
前端
静默回滚36 分钟前
浏览器能显示AVIF,却导不出一张AVIF
前端
itmigrate40 分钟前
PHP 导出大 CSV 时内存溢出的一次排查
android·开发语言·php