鸿蒙学习记录

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

相关推荐
钛态2 小时前
AI 辅助:前端框架反模式:过度封装、状态滥用与副作用失控
前端·vue·react·web
by__csdn2 小时前
Vue vs React vs Angular:前端框架终极对决
前端·vue.js·react.js·前端框架·vue·react·angular
钛态2 小时前
前端框架选型决策框架:React、Vue、Svelte、Solid 的 2026 年横评
前端·vue·react·web
2501_926102862 小时前
深入浅出Vue.js前端框架设计:核心原理与实践指南
前端·vue.js·前端框架
程序员黑豆3 小时前
使用AI编程开发鸿蒙应用:从环境搭建到实战示例
前端·harmonyos
郑州光合科技余经理6 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
程序员黑豆7 小时前
鸿蒙应用开发:一次开发多端部署之响应式布局完全指南
前端·harmonyos
小月土星7 小时前
2.0 React Router 前端路由深度解析:从传统后端路由到现代 SPA 的完整演进
前端
To_OC8 小时前
LC 35 搜索插入位置:二分查找谁都会,边界条件谁写谁懵
javascript·算法·leetcode
码哥DFS9 小时前
二叉树的直径
开发语言·javascript·算法