鸿蒙学习记录

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

相关推荐
程序员老陆5 分钟前
Qt::WidgetAttribute 常用属性详解
开发语言·qt
可爱的秋秋啊9 分钟前
vue调用腾讯人脸组件封装+接口请求后端调用
前端·javascript·vue.js
程序员爱钓鱼13 分钟前
Rust 生命周期常见错误详解:看懂编译器报错并正确修复
前端·后端·rust
zhanghaha131414 分钟前
Python进阶教程:5_XML 解析 —— 新手完全指南
java·前端·数据库
绝世唐门三哥22 分钟前
CSS 虚线下划线用法指南:text-decoration 完整解析
前端·javascript·css
程序员爱钓鱼26 分钟前
Go if 判断详解
前端·后端·go
程序员黑豆29 分钟前
Java字符串拼接全解析:6种方式性能对比与实战指南
java·前端·ai编程
苏灿烤鱼34 分钟前
14MB 模型,凭什么跟 270M 对打?
javascript·python·agent
特立独行的猫a2 小时前
Windows安装Rust环境 Clang替代GCC MinGW环境LLVM工具链(详细教程)
开发语言·windows·rust·mingw·环境搭建·llvm
万少5 小时前
DeepSeek 昨晚刚开源了 Harness:附万少的2 万字保姆级教程
前端·后端·架构