React JS 实现日历月首尾空白占位填充 对齐周日起始网格
日历首尾空位填充实现方案
核心逻辑说明
JS原生Date实例的getDay()方法返回值为0~6,分别对应周日到周六,完全匹配你从周日开始排列的网格规则:
- 前置空位数量:直接取当月首日的
getDay()值。比如首日为周二时getDay()返回2,就在日期数组开头补2个空对象,对应周日、周一的空位 - 后置空位数量:用
6减去当月末日的getDay()值。比如末日为周四时getDay()返回4,需要补6-4=2个空对象,对应周五、周六的空位
优化后完整代码
import React, { useEffect, useState, useCallback } from "react"; import "./styles.css"; // 公共获取月份日期数组的方法,避免重复逻辑 const getMonthDates = (targetMonthOffset = 0) => { const now = new Date(); // 处理月份跨年溢出问题,Date构造函数会自动进位/退位 const firstDay = new Date(now.getFullYear(), now.getMonth() + targetMonthOffset, 1); const lastDay = new Date(firstDay.getFullYear(), firstDay.getMonth() + 1, 0); const calendarMonth = firstDay.toLocaleString("en-us", { month: "long", year: "numeric" }); // 生成当月完整日期数组 const monthDates = []; for (let d = new Date(firstDay); d <= lastDay; d.setDate(d.getDate() + 1)) { monthDates.push(new Date(d)); } // 计算首尾空位数量并生成占位对象 const prefixEmptyCount = firstDay.getDay(); const suffixEmptyCount = 6 - lastDay.getDay(); const prefixEmpty = Array(prefixEmptyCount).fill({}); const suffixEmpty = Array(suffixEmptyCount).fill({}); // 合并最终用于渲染的日期数组 const finalDates = [...prefixEmpty, ...monthDates, ...suffixEmpty]; return { calendarMonth, finalDates }; }; export default function App() { // 用偏移量存储当前可见月份,避免闭包问题 const [monthOffset, setMonthOffset] = useState(0); const [calData, setCalData] = useState(null); const [dates, setDates] = useState(null); // 切换月份的公共处理逻辑 const updateMonth = useCallback((newOffset) => { const { calendarMonth, finalDates } = getMonthDates(newOffset); setCalData(calendarMonth); setDates(finalDates); }, []); useEffect(() => { updateMonth(monthOffset); }, [monthOffset, updateMonth]); return ( <div className="App"> <h1>{calData}</h1> <button onClick={() => setMonthOffset(prev => prev - 1)}>Prev Month</button> <button onClick={() => setMonthOffset(prev => prev + 1)}>Next Month</button> {dates && dates.map((item, i) => { // 空对象渲染空位,正常日期渲染内容 return <div key={i}>{Object.keys(item).length ? item.toString() : ""}</div>; })} </div> ); }
额外优化说明
- 废弃了原代码中冗余的
async/await逻辑,日期循环本身为同步操作,不需要异步封装 - 修复了原代码中切换月份时的闭包问题:原
setVisibleMonth((state) => visibleMonth - 1)实际引用的是外层旧的visibleMonth值,改用prev => prev -1的函数式更新可保证状态计算正确 - 抽出重复的日期计算逻辑,避免在三个切换月份的方法中重复编写相同代码
内容的提问来源于stack exchange,提问作者Rob Terrell
相关产品推荐
相关产品推荐

