基于React实现无限滚动的日历详细教程,附源码【手写日历教程第二篇】

前言

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

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

实现步骤

渲染单个月日历

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

尝试同时渲染多个月份

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

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

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

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号都是在第一列的情况。

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个月份成功渲染出来了,接下来我们通过列表滚动加载的思路,分别监听列表滚动置顶滚动触底这两个时机。

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>

在这里插入图片描述

总结

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐闻x

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值