鸿蒙开发的精髓,不止在于可以"一次开发,多端部署",更关键的是------组件化能力超强!本篇文章带你构建一个可复用的「信息卡片组件」,掌握 HarmonyOS ArkTS 的组件化开发精髓!
🎯 一、目标效果
实现一个通用的信息卡片组件,具备以下能力:
- 支持标题、副标题展示
- 可自定义图标
- 可响应点击事件
- 实现组件复用(传入不同参数即可渲染不同内容)
最终效果示意:
css
[📦] 今日订单
已完成:123单
🧱 二、项目结构预设
markdown
- pages/
- Index.ets // 主页面,引用组件
- components/
- InfoCard.ets // 自定义信息卡片组件
🧩 三、创建组件 InfoCard
路径:components/InfoCard.ets
less
@Component
export struct InfoCard {
@Prop title: string
@Prop subtitle: string
@Prop icon: string
@Prop onTap: () => void
build() {
Row() {
Text(this.icon).fontSize(28).margin({ right: 12 })
Column() {
Text(this.title).fontSize(18).fontWeight(FontWeight.Bold)
Text(this.subtitle).fontSize(14).margin({ top: 4 }).opacity(0.6)
}
.justifyContent(FlexAlign.Center)
}
.padding(16)
.backgroundColor('#f5f5f5')
.borderRadius(12)
.width('90%')
.margin({ top: 8, bottom: 8 })
.onClick(() => this.onTap?.())
}
}
✅ 核心点:
- 使用
@Prop
实现组件参数传递 - 使用
onClick
响应用户交互 - UI 布局使用
Row
+Column
组合,轻量易读
🧪 四、在主页中使用组件
路径:pages/Index.ets
less
import InfoCard from '../components/InfoCard'
@Entry
@Component
struct Index {
build() {
Column() {
InfoCard({
icon: '📦',
title: '今日订单',
subtitle: '已完成:123单',
onTap: () => {
console.log('点击了订单卡片')
}
})
InfoCard({
icon: '💰',
title: '本月收入',
subtitle: '¥18,250',
onTap: () => {
console.log('点击了收入卡片')
}
})
}
.width('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
.height('100%')
.backgroundColor('#ffffff')
}
}
📌 五、实操总结
技术点 | 说明 |
---|---|
@Prop |
定义可传入参数,类似 props |
onClick |
原生支持点击事件 |
组件封装 | 类似 React/Vue 的组件化思想 |
样式控制 | 使用 ArkTS 声明式语法完成布局与样式 |
📦 六、拓展优化建议
你可以进一步扩展组件功能,如:
- 支持图标图片 URL(
Image
渲染) - 支持背景色动态配置
- 添加右侧操作按钮(如「查看」)
📘 下篇预告
《状态驱动开发入门:玩转 @State 与 @Provide》------带你深入鸿蒙响应式架构的本质,教你如何构建多组件共享状态!