鸿蒙学习记录

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

相关推荐
情深不寿3175 分钟前
C++特殊类的设计
开发语言·c++·单例模式
DoraBigHead9 分钟前
React 中的代数效应:从概念到 Fiber 架构的落地
前端·javascript·react.js
LuckySusu9 分钟前
【vue篇】Vue 性能优化全景图:从编码到部署的优化策略
前端·vue.js
卓伊凡13 分钟前
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓
前端
笨笨鸟慢慢飞16 分钟前
Vue3后退不刷新,前进刷新
前端
流星白龙18 分钟前
【Qt】3.认识 Qt Creator 界面
java·开发语言·qt
LuckySusu18 分钟前
【vue篇】SSR 深度解析:服务端渲染的“利”与“弊”
前端·vue.js
LuckySusu18 分钟前
【vue篇】SPA 单页面应用:现代 Web 的革命与挑战
前端·vue.js
LuckySusu19 分钟前
【vue篇】Vue 初始化页面闪动(FOUC)问题终极解决方案
前端·vue.js
fruge21 分钟前
从 0 到 1 理解前端工程化:图表化解析核心逻辑
前端