🎯 目标
封装一个通用信息卡片组件 InfoCard
,适用于:
-
内容展示卡片(如文章、商品、用户信息)
-
图 + 文 + 操作按钮结构统一
-
卡片具备圆角、阴影、点击反馈等样式
-
支持插槽式标题、底部按钮扩展
-
支持加载状态、内容折叠、多列布局等
🧱 样式结构示意
╭────────────╮
│ 🖼 图 | 标题 + 简介 │
│ | 描述内容 │
│ | [查看详情] [删除] │
╰────────────╯
🧰 组件实现:InfoCard.ets
@Component
export struct InfoCard {
@Prop image: string = ''
@Prop title: string = ''
@Prop description: string = ''
@Prop actions: Array<{ text: string; onClick: () => void }> = []
build() {
Row()
.padding(12)
.backgroundColor('#fff')
.borderRadius(12)
.shadow({ radius: 6, color: '#00000010' })
.alignItems(VerticalAlign.Top)
.width('100%') {
// 左侧图片
Image(this.image)
.width(80)
.height(80)
.borderRadius(8)
.objectFit(ImageFit.Cover)
// 右侧内容区
Column()
.margin({ left: 12 })
.flexGrow(1)
.justifyContent(FlexAlign.SpaceBetween) {
Column({ space: 6 }) {
Text(this.title).fontSize(16).fontWeight(FontWeight.Bold).fontColor('#333')
Text(this.description).fontSize(13).fontColor('#666').maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis })
}
if (this.actions.length > 0) {
Row({ space: 12 }).margin({ top: 8 }) {
this.actions.forEach(act =>
Button(act.text)
.type(ButtonType.Normal)
.fontSize(12)
.onClick(() => act.onClick())
)
}
}
}
}
}
}
📦 使用示例
@Entry
@Component
struct DemoInfoCard {
build() {
Column({ space: 20 }) {
InfoCard({
image: 'https://example.com/book.jpg',
title: 'HarmonyOS 入门指南',
description: '从安装到实战,全面掌握鸿蒙应用开发核心能力。',
actions: [
{ text: '查看详情', onClick: () => ToastManager.show('查看详情') },
{ text: '删除', onClick: () => ToastManager.show('已删除', 'warning') }
]
})
InfoCard({
image: 'https://example.com/avatar.jpg',
title: '张三 · 开发者',
description: '擅长 ArkTS / JS / HarmonyOS 分布式组件开发。',
actions: [
{ text: '发消息', onClick: () => ToastManager.show('发起对话') }
]
})
}.padding(20)
}
}
✨ 可扩展能力建议
功能 | 说明 |
---|---|
加载骨架屏支持 | 接入 Loading Skeleton 占位卡片 |
卡片状态切换支持(禁用/选中) | 支持状态样式切换,添加选中高亮/不可点击样式 |
多列卡片布局支持 | 与 Wrap /Grid 搭配呈现多列卡片 |
插槽扩展内容区域 | 支持插入 tags、评级星星、价格、badge 等附加信息 |
📘 下一篇预告
第34篇:【HarmonyOS 5.0.0 或以上】构建分页容器组件 PageContainer:支持分页请求 / 上拉加载 / 空数据处理