鸿蒙学习记录

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

相关推荐
码界奇点21 小时前
Java设计模式精讲从基础到实战的常见模式解析
java·开发语言·设计模式·java-ee·软件工程
卷福同学21 小时前
【AI编程】用Codebuddy+lighthouse开发AI年龄模拟网站
javascript·后端
四维碎片21 小时前
【Qt】配置安卓开发环境
android·开发语言·qt
源力祁老师21 小时前
Odoo 19 制造与会计集成深度解析
前端·javascript·制造
西游音月21 小时前
(7)框架搭建:Qt实战项目之主窗体导航栏、状态栏
开发语言·qt
3***499621 小时前
Swift Experience
开发语言·ios·swift
iFlow_AI21 小时前
iFlow CLI Hooks 「从入门到实战」应用指南
开发语言·前端·javascript·人工智能·ai·iflow·iflow cli
Maybyy1 天前
Chart.js图标绘制工具库
开发语言·javascript·ecmascript
漂流瓶jz1 天前
SourceMap数据生成核心原理:简化字段与Base64VLQ编码
前端·javascript·算法
桜吹雪1 天前
手搓一个简易Agent
前端·人工智能·后端