3、构建你的第一个鸿蒙组件化 UI 页面:实现可复用的卡片组件(附实战代码)


鸿蒙开发的精髓,不止在于可以"一次开发,多端部署",更关键的是------组件化能力超强!本篇文章带你构建一个可复用的「信息卡片组件」,掌握 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》------带你深入鸿蒙响应式架构的本质,教你如何构建多组件共享状态!


相关推荐
wuyikeer23 分钟前
Spring Framework 中文官方文档
java·后端·spring
Victor35627 分钟前
MongoDB(61)如何避免大文档带来的性能问题?
后端
Victor35637 分钟前
MongoDB(62)如何避免锁定问题?
后端
wuyikeer1 小时前
Spring BOOT 启动参数
java·spring boot·后端
~无忧花开~2 小时前
React生命周期全解析
开发语言·前端·javascript·react.js·前端框架·react
小白学鸿蒙2 小时前
串口通信发送后无响应|极简排查步骤(实战总结)
华为·harmonyos
子木HAPPY阳VIP2 小时前
Ubuntu 22.04 VMware 设置固定IP配置
人工智能·后端·目标检测·机器学习·目标跟踪
人间打气筒(Ada)2 小时前
如何基于 Go-kit 开发 Web 应用:从接口层到业务层再到数据层
开发语言·后端·golang
开心就好20252 小时前
使用Wireshark进行TCP数据包抓包分析:三次握手与四次挥手详解
后端·ios