鸿蒙学习记录

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

相关推荐
jimy16 分钟前
拷贝构造时,不用引用的话,按值传参会无限递归调用拷贝构造函数
开发语言
LccKyI9 分钟前
# C# 基础编程 面试题汇总(一)
开发语言·c#
计算机魔术师11 分钟前
AI开源社区迎来最大并购案:Hugging Face以129亿美元估值入局英伟达
前端
CODER030412 分钟前
win11系统编译安装cuda版llama-cpp-python(踩完所有的坑)
开发语言·python·llama
mayaairi15 分钟前
JS DOM与事件处理完全指南
服务器·前端·javascript
神仙别闹17 分钟前
基于C语言+SQLite 实现(控制台+图形界面)图书管理系统
c语言·开发语言·sqlite
恋猫de小郭28 分钟前
Firebase 如何让全球 Android 和 Flutter 开发者集体 Build Fail
android·前端·flutter
墨白曦煜28 分钟前
智能体架构范式总结(React、Plan-And-Solve、Reflection)
前端·react.js·前端框架
何以解忧,唯有..29 分钟前
LangChain 模型调用方法总结:invoke、batch、stream 的入参与出参
开发语言·langchain·batch
qq_4260039632 分钟前
多语言新增语种全量测试策略的测试范围
前端·javascript·python·自动化