月份切换与年份导航:prevMonth / nextMonth 逻辑

📅 2026/7/19 1:10:29
月份切换与年份导航:prevMonth / nextMonth 逻辑
前言在日历应用中月份切换是最基本的交互。“海风日记“的日历页通过左右箭头按钮实现月份切换同时支持“今天“按钮快速回到当月。本文将从源码出发深入讲解月份切换的逻辑实现和边界处理。一、月份切换实现1.1 状态变量Component export struct CalendarTab { State curYear: number new Date().getFullYear() State curMonth: number new Date().getMonth() // 0-indexed private todayDate new Date().getDate() private todayMonth new Date().getMonth() private todayYear new Date().getFullYear() }1.2 上个月private prevMonth() { if (this.curMonth 0) { this.curYear - 1 // 跨年 this.curMonth 11 // 十二月 } else { this.curMonth - 1 } }1.3 下个月private nextMonth() { if (this.curMonth 11) { this.curYear 1 // 跨年 this.curMonth 0 // 一月 } else { this.curMonth 1 } }二、导航按钮Row({ space: 12 }) { // 左箭头 Button() { SymbolGlyph($r(sys.symbol.chevron_left)).fontSize(16).fontColor([COLOR_TEXT_MAIN]) } .backgroundColor(transparent).width(36).height(36) .onClick(() { this.prevMonth() }) // 月份标题 Column({ space: 2 }) { Text(this.getMonthName(this.curMonth)) .fontSize(22).fontColor(COLOR_TEXT_MAIN).fontWeight(FontWeight.Bold) Text(${this.curYear}年).fontSize(12).fontColor(COLOR_TEXT_SECONDARY) } .alignItems(HorizontalAlign.Center) // 右箭头 Button() { SymbolGlyph($r(sys.symbol.chevron_right)).fontSize(16).fontColor([COLOR_TEXT_MAIN]) } .backgroundColor(transparent).width(36).height(36) .onClick(() { this.nextMonth() }) }三、“今天“按钮Button(今天) .height(30).fontSize(13).fontColor(#FFFFFF).fontWeight(FontWeight.Bold) .backgroundColor(COLOR_PRIMARY).borderRadius(15) .padding({ left: 12, right: 12 }) .onClick(() { this.curYear this.todayYear this.curMonth this.todayMonth })四、年视图的年份导航Row({ space: 4 }) { Button() { SymbolGlyph($r(sys.symbol.chevron_left)).fontSize(16).fontColor([COLOR_AMBER]) } .backgroundColor(transparent).width(36).height(36) .onClick(() { this.curYear - 1 }) Button() { SymbolGlyph($r(sys.symbol.chevron_right)).fontSize(16).fontColor([COLOR_AMBER]) } .backgroundColor(transparent).width(36).height(36) .onClick(() { this.curYear 1 }) }五、常见问题5.1 月份切换后 UI 不更新问题点击切换按钮后月份数字没有变化。原因State变量更新了但 UI 未重新渲染。解决方案确保curYear和curMonth是State变量。总结本文通过“海风日记“的日历页深入讲解了月份切换的实现prevMonth/nextMonth月份切换逻辑跨年处理边界情况处理“今天“按钮快速回到当月年视图导航年份切换下一篇文章将深入讲解月统计面板敬请期待。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源State 装饰器文档SymbolGlyph 文档Button 组件文档海风日记项目源码[HarmonyOS 开发者官网](https://atomgit.com/openharmony/docs开源鸿蒙跨平台社区