
前言日历组件是许多应用中的核心 UI 元素。在小事记xiaoshiji_ohos_app 的CalendarViewPage.ets中使用 Grid 手写实现了一个完整的日历组件包括日期网格、事件标记点、日期选中状态和月份切换功能。本文深入解析日历组件的实现原理和关键代码。本文参考 HarmonyOS 官方文档Grid 组件 和 日期计算。一、日历组件的核心逻辑1.1 日期计算// 日期计算工具函数 function getDaysInMonth(year: number, month: number): number { return new Date(year, month, 0).getDate(); } function getFirstDayOfMonth(year: number, month: number): number { return new Date(year, month - 1, 1).getDay(); } function generateCalendarDays(year: number, month: number): number[] { const daysInMonth getDaysInMonth(year, month); const firstDay getFirstDayOfMonth(year, month); const days: number[] []; // 填充前导空白 for (let i 0; i firstDay; i) { days.push(0); } // 填充日期 for (let i 1; i daysInMonth; i) { days.push(i); } // 填充尾部空白补齐到 6 行 42 格 while (days.length 42) { days.push(0); } return days; }方案适用场景注意事项方案一简单场景实现简单易于维护方案二复杂场景灵活性高需注意性能方案三特殊场景针对特定需求优化二、日历的完整实现2.1 日历组件// CalendarViewPage.ets — 完整日历组件 Entry Component export struct CalendarViewPage { State currentMonth: number 5; State currentYear: number 2024; State selectedDay: number 20; State events: CalendarEvent[] getMockCalendarEvents(); private weekDays: string[] [日, 一, 二, 三, 四, 五, 六]; private eventDays: number[] [1, 12, 20]; get calendarDays(): number[] { return generateCalendarDays(this.currentYear, this.currentMonth); } build() { Column() { // 月份导航 this.buildMonthHeader() // 星期标题 this.buildWeekHeader() // 日期网格 this.buildCalendarGrid() // 事件列表 this.buildEventList() } .width(100%) .height(100%) .backgroundColor(Color.White) } Builder buildMonthHeader() { Row() { Text() .fontSize(20) .fontColor(#1A1A2E) .onClick(() { this.previousMonth(); }) Blank() Text(${this.currentYear}年${this.currentMonth}月) .fontSize(18) .fontWeight(FontWeight.Bold) Blank() Text() .fontSize(20) .fontColor(#1A1A2E) .onClick(() { this.nextMonth(); }) } .width(100%) .padding({ left: 20, right: 20, top: 10, bottom: 10 }) } Builder buildWeekHeader() { Row() { ForEach(this.weekDays, (day: string) { Text(day) .fontSize(13) .fontColor(#9CA3AF) .width(14.28%) .textAlign(TextAlign.Center) }, (day: string) day) } .width(100%) .padding({ top: 8, bottom: 8 }) } Builder buildCalendarGrid() { Grid() { ForEach(this.calendarDays, (day: number, index: number) { GridItem() { if (day 0) { Column() { Text(day.toString()) .fontSize(15) .fontColor(this.selectedDay day ? Color.White : #1A1A2E) .fontWeight(this.selectedDay day ? FontWeight.Bold : FontWeight.Normal) if (this.eventDays.includes(day)) { Circle().width(4).height(4).fill(#7B68EE).margin({ top: 2 }) } } .width(40) .height(40) .justifyContent(FlexAlign.Center) .backgroundColor(this.selectedDay day ? #7B68EE : Color.Transparent) .borderRadius(20) .onClick(() { this.selectedDay day; }) } } }, (day: number, index: number) ${index}) } .columnsTemplate(1fr 1fr 1fr 1fr 1fr 1fr 1fr) .rowsGap(4) .width(100%) .padding({ left: 8, right: 8 }) } Builder buildEventList() { Column({ space: 0 }) { ForEach(this.events, (event: CalendarEvent) { Row() { Text(event.date.split(-)[2]) .fontSize(14) .fontColor(#7B68EE) .width(40) .fontWeight(FontWeight.Bold) Column({ space: 2 }) { Text(event.title).fontSize(15).fontColor(#1A1A2E) Text(event.time).fontSize(12).fontColor(#9CA3AF) } .margin({ left: 12 }) .layoutWeight(1) } .width(100%) .padding({ left: 20, right: 20, top: 12, bottom: 12 }) }, (event: CalendarEvent) event.id) } .width(100%) .layoutWeight(1) } private previousMonth(): void { if (this.currentMonth 1) { this.currentMonth 12; this.currentYear--; } else { this.currentMonth--; } } private nextMonth(): void { if (this.currentMonth 12) { this.currentMonth 1; this.currentYear; } else { this.currentMonth; } } }三、事件标记点3.1 标记点的实现// 事件标记点的实现 if (this.eventDays.includes(day)) { Circle() .width(4) .height(4) .fill(#7B68EE) // 紫色标记点 .margin({ top: 2 }) }3.2 标记点的样式属性值说明颜色#7B68EE紫色与主题色一致大小4x4小巧不干扰日期显示位置日期下方 2vp与日期文字保持距离四、常见问题4.1 日期计算错误问题getDaysInMonth返回的天数不正确。解决方案使用new Date(year, month, 0)获取当月的最后一天。4.2 网格对齐问题问题日期网格与星期标题未对齐。解决方案确保两者使用相同的宽度分配方式。五、// 异步操作示例 async function handleAsync(): Promisevoid { try { const result await this.loadData(); this.data result; } catch (err) { console.error(加载失败, err); } }扩展功能5.1 月份切换动画// 月份切换动画 private async switchMonth(forward: boolean): Promisevoid { animateTo({ duration: 200 }, () { if (forward) { this.nextMonth(); } else { this.previousMonth(); } }); }八、拓展阅读本节汇总了与本文主题相关的扩展阅读材料帮助读者深入理解相关技术细节。8.1 官方文档开发者指南HarmonyOS 应用开发概述API 参考ArkTS API 参考8.2 相关技术文章性能优化最佳实践常见问题排查指南8.3 社区资源开源鸿蒙跨平台社区https://openharmonycrossplatform.csdn.net十、最佳实践与优化建议在实际开发中合理运用上述技术可以显著提升应用的性能和用户体验。以下是几个关键的最佳实践建议10.1 性能优化要点优化方向具体措施预期效果渲染性能减少不必要的组件重建提升帧率内存管理及时释放不再使用的资源降低内存占用响应速度避免在主线程执行耗时操作提升交互流畅度10.2 推荐实践步骤按照以下步骤进行优化使用 DevEco Studio 的 Profiler 工具分析当前性能瓶颈针对识别出的热点进行针对性优化通过单元测试和集成测试验证优化效果在真机环境下进行回归测试10.3 代码示例// 推荐的最佳实践示例 Component export struct OptimizedComponent { // 使用 State 管理最小粒度的状态 State private isActive: boolean false; build() { Column() { Text(this.isActive ? 激活 : 未激活) .fontSize(16) } .onClick(() { // 使用 animateTo 实现平滑过渡 animateTo({ duration: 300 }, () { this.isActive !this.isActive; }); }); } }最佳实践提示在编写代码时始终遵循 ArkUI 的性能优化原则避免在 build() 方法中执行复杂计算或频繁的状态更新。总结// 类型定义示例 interface ApiResponseT { code: number; message: string; data: T; } async function fetchDataT(url: string): PromiseApiResponseT { const response await fetch(url); return response.json(); }本文深入解析了日历组件的手写实现。核心要点如下日期计算使用getDaysInMonth和getFirstDayOfMonth计算日期Grid 网格7列等宽布局40x40 的日期格子事件标记点4x4 的紫色圆点标记有事件的日期月份切换通过修改currentMonth和currentYear实现月份切换如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力九、完整示例代码9.1 完整组件实现以下是一个完整的组件实现示例展示了本文介绍的各个技术点的综合运用import { Component, State, Prop } from kit.ArkUI; Component export struct DemoComponent { Prop title: string ; State count: number 0; build() { Column({ space: 12 }) { // 标题区域 Text(this.title) .fontSize(18) .fontWeight(FontWeight.Bold) .fontColor(#1A1A2E) .width(100%) // 内容区域 Text(当前计数: ${this.count}) .fontSize(14) .fontColor(#6B7280) // 交互按钮 Button(点击增加) .width(120) .height(40) .backgroundColor(#7B68EE) .borderRadius(20) .fontColor(Color.White) .onClick(() { this.count; }) } .width(100%) .padding(16) .backgroundColor(Color.White) .borderRadius(12) .shadow({ radius: 4, color: #00000008, offsetX: 0, offsetY: 2 }) } }9.2 使用方式在页面中引入并使用该组件Entry Component struct Index { build() { Column() { DemoComponent({ title: 示例组件 }) } .width(100%) .height(100%) .backgroundColor(#F8F9FA) } }9.3 代码说明组件封装使用Component装饰器定义可复用的组件状态管理使用State管理组件内部状态参数传递使用Prop接收外部传入的参数事件处理使用onClick处理用户交互样式优化使用borderRadius、shadow等属性美化 UI相关资源官方文档 - 开发者指南HarmonyOS 应用开发官方文档 - ArkUI 组件参考ArkUI 组件官方文档 - API 参考API 参考官方文档 - 状态管理状态管理概述官方文档 - 动画动画概述官方文档 - 网络管理网络管理官方文档 - 数据管理数据管理开源鸿蒙跨平台社区https://openharmonycrossplatform.csdn.net