鸿蒙学习记录

创建了一个名为 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 小时前
聊聊设计模式在 Vue 3 业务开发中的落地——从一次代码重构说起
前端·架构
Cricyta Sevina5 小时前
Java 语言多线程核心概念全解析
java·开发语言
缘三水6 小时前
【C语言】15.指针(5)
c语言·开发语言·指针·语法
爱吃大芒果6 小时前
从零开始学 Flutter:状态管理入门之 setState 与 Provider
开发语言·javascript·flutter
shenzhenNBA6 小时前
如何在python文件中使用日志功能?简单版本
java·前端·python·日志·log
掘金泥石流6 小时前
分享下我创业烧了 几十万的 AI Coding 经验
前端·javascript·后端
用户47949283569156 小时前
JavaScript 为什么选择原型链?从第一性原理聊聊这个设计
前端·javascript
清风拂山岗 明月照大江6 小时前
简单文件 IO 示例:使用系统调用读写文件
开发语言·c++·算法
技术净胜6 小时前
MATLAB文本文件读写实操fopen/fscanf/fprintf/fclose全解析
开发语言·matlab