鸿蒙学习记录

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

相关推荐
奔跑吧邓邓子1 分钟前
【Python爬虫(34)】Python多进程编程:开启高效并行世界的钥匙
开发语言·爬虫·python·多进程
Heris9928 分钟前
2.22 c++练习【operator运算符重载、封装消息队列、封装信号灯集】
开发语言·c++
----云烟----30 分钟前
C/C++ 中 volatile 关键字详解
c语言·开发语言·c++
yuanpan1 小时前
23种设计模式之《组合模式(Composite)》在c#中的应用及理解
开发语言·设计模式·c#·组合模式
BanLul1 小时前
进程与线程 (三)——线程间通信
c语言·开发语言·算法
十八朵郁金香1 小时前
【JavaScript】深入理解模块化
开发语言·javascript·ecmascript
m0_748230941 小时前
Redis 通用命令
前端·redis·bootstrap
Hello.Reader1 小时前
深入理解 Rust 的 `Rc<T>`:实现多所有权的智能指针
开发语言·后端·rust
程序员阿鹏1 小时前
jdbc批量插入数据到MySQL
java·开发语言·数据库·mysql·intellij-idea
yoona10201 小时前
Rust编程语言入门教程(八)所有权 Stack vs Heap
开发语言·后端·rust·区块链·学习方法