乐闻世界logo
搜索文章和话题
【手写组件库之日历组件教程第二篇】基于React实现无限滚动的日历详细教程,附在线DEMO与源码

【手写组件库之日历组件教程第二篇】基于React实现无限滚动的日历详细教程,附在线DEMO与源码

乐闻的头像
乐闻

2023年08月24日 10:32· 阅读 1157

前言

最常见的日历大部分都是滚动去加载更多的月份,而不是让用户手动点击按钮切换日历月份。滚动加载的交互方式对于用户而言是更加丝滑和舒适的,没有明显的操作割裂感。

那么现在需要做一个这样的无限滚动的日历,前端开发者应该如何去思考和代码实现呢?下面我会详细的介绍实现思路和步骤。

在线演示DEMO

https://calendar.levenx.com/#/scroll-calendar

实现步骤

渲染单个月日历

如何对于如何实现单个月份的日历没有思路的同学需要先阅读一下这篇简单日历的实现教程https://blog.csdn.net/m0_37890289/article/details/132457676;通过阅读这篇教程可以实现单月的渲染。

尝试同时渲染多个月份

对于无限滚动的日历,其实就是把所有的月份都放在一个列表中,然后用户滚动这个列表就行了,也就是我们想要的丝滑的切换日历。但是实现的话肯定不能真的把所有的月份都提前准备好,而且谁能知道未来有多少月。

所以这里可以利用滚动加载的方式进行月份数据的加载和列表数据的组装,关于滚动加载,我之前也写过一篇教程,没有思路的同学可以参考一下。https://blog.csdn.net/m0_37890289/article/details/130774836

好,那么好,接下来我们就开始动手实现这个无限滚动的日历。首先我们先尝试渲染3个月,当前月,当前前一个月,当前后一个月。

json
import "./index.css"; import { getDaysOfMonth } from "../../utils"; import { useCallback, useMemo, useState } from "react"; import dayjs, { Dayjs } from "dayjs"; import "dayjs/locale/zh-cn"; dayjs.locale("zh-cn"); function ScrollCalendar() { // 获取月的所有日期 const getDays = useCallback((month: Dayjs) => { return getDaysOfMonth(month.year(), month.month() + 1); }, []); // 定义好整个列表 const [schedules, setSchedules] = useState(() => { return [dayjs().subtract(1, "month"), dayjs(), dayjs().add(1, "month")].map( month => ({ month, days: getDays(month), }), ); }); const weekTitles = useMemo(() => { return [...Array(7)].map((_, weekInx) => { return dayjs().day(weekInx); }); }, []); return ( <div className="App"> <div className="calendar"> <div className="calendar-title"> {weekTitles.map(title => { return <div className="calendar-week">{title.format("dd")}</div>; })} </div> {schedules.map(schedule => { return ( <div> <div className="calendar-month"> <div>{schedule.month.format("MMM YYYY")}</div> </div> <div className="calendar-content"> {schedule.days.map(day => { return <div className="calendar-day">{day.format("DD")}</div>; })} </div> </div> ); })} </div> </div> ); } export default ScrollCalendar;

虽然多个月份的日历列表是渲染出来,但是看起来很奇怪,由于我们之前为了让单个月份的数据看起来完成,我们将上个月和下个月的数据填充到当前月,让日历看起来比较完整。

但是如果同时渲染多个月份,还将相邻月份的日期拿来填充,这肯定是不合理的。那么我们应该数据源头进行调整。接下来我们调整一下获取某一个月内所有日期的工具方法 getDaysOfMonth

  • 关键步骤

    非当前月就填充null,要把位置占住,不然又要出现每个月的1号都是在第一列的情况。

json
import dayjs from "dayjs"; export const getDaysOfMonth = (year: number, month: number) => { let firstDayOfMonth = dayjs(`${year}-${month}-1`); let lastDayOfMonth = dayjs(`${year}-${month + 1}-1`).subtract(1, "day"); // 开始补全第一天前的日期 while (firstDayOfMonth.day() !== 0) { firstDayOfMonth = firstDayOfMonth.subtract(1, "day"); } // 开始补全最后一天后的日期 while (lastDayOfMonth.day() !== 6) { lastDayOfMonth = lastDayOfMonth.add(1, "day"); } const days = []; const currentMonth = dayjs(`${year}-${month}-1`); let tempDate = firstDayOfMonth; while (tempDate.isBefore(lastDayOfMonth) || tempDate.isSame(lastDayOfMonth)) { // 关键步骤,非当前月就填充null,要把位置占住,不然又要出现每个月的1号都是在第一列的情况 **if (tempDate.isSame(currentMonth, "month")) { days.push(tempDate); } else { days.push(null); }** tempDate = tempDate.add(1, "day"); } return days; };

让日历列表滚动起来

上面我们已经成功将3个月份成功渲染出来了,接下来我们通过列表滚动加载的思路,分别监听列表滚动置顶滚动触底这两个时机。

json
const calendarRef = useRef<HTMLDivElement>(null); useEffect(() => { let prevScrollHeight = 0; const scrollEvent = debounce(async e => { let scrollHeight = e.target.scrollHeight; let scrollTop = e.target.scrollTop; let offsetHeight = e.target.offsetHeight; if (scrollTop < 100) { console.log("列表置顶"); setSchedules(schedules => { const lastSchedule = schedules[0]; const prevMonth = lastSchedule.month.subtract(1, "month"); const prevSchedule = { month: prevMonth, days: getDays(prevMonth), }; return [prevSchedule, ...schedules]; }); const targetScrollTop = scrollTop + (scrollHeight - prevScrollHeight) + 50; calendarRef.current?.scrollTo({ top: targetScrollTop }); // 记录前一个滚动高度 prevScrollHeight = scrollHeight; } if (offsetHeight + scrollTop >= scrollHeight - 10) { console.log("列表触底,触发接口请求数据"); setSchedules(schedules => { const lastSchedule = schedules[schedules.length - 1]; const nextMonth = lastSchedule.month.add(1, "month"); const nextSchedule = { month: nextMonth, days: getDays(nextMonth), }; return [...schedules, nextSchedule]; }); } }, 100); calendarRef.current?.addEventListener("scroll", scrollEvent); return () => { if (calendarRef.current) { } }; }, []); <div className="calendar" style={{ height: "100vh", overflowY: "scroll", }} ref={calendarRef}> ... </div>

s

总结

本文实现了无限滚动的日历组件,满足了很大一部分需求的基础,有需要的同学可基于源码进行二次修改。有任何问题都可以进行留言,如何文章对你有帮忙,可以帮我点个赞🦉。源码链接https://github.com/levenx/react-calendar-training/tree/main/src/pages/scroll-calendar

感兴趣的可访问DEMO页面https://calendar.levenx.com/#/scroll-calendar

标签: