如何让FullCalendar timeGridWeek视图打印当前滚动显示的内容
问题解决:FullCalendar timeGridWeek视图打印当前滚动内容
问题场景
在React项目中使用FullCalendar的timeGridWeek视图时,点击自定义打印按钮后,仅能打印从午夜开始的日历顶部内容,无法打印当前用户滚动到的视图区域。
解决方案
核心思路是在打印前获取当前日历的滚动时间,临时修改日历的scrollTime属性匹配当前滚动位置,打印完成后恢复初始设置,确保打印内容与当前视图一致。
修改步骤
- 用状态保存初始的
scrollTime值,方便打印后恢复 - 在打印触发时,通过FullCalendar实例的
getScrollTime()方法获取当前滚动的时间 - 更新日历的
scrollTime为当前滚动时间,等待视图更新后执行打印 - 打印完成后恢复初始的
scrollTime设置
修改后的完整代码
import FullCalendar from '@fullcalendar/react'; import { useEffect, useRef, useState } from 'react'; import { useReactToPrint } from 'react-to-print'; const events: any[] = []; const INITIAL_SCROLL_TIME = "07:00:00"; // 初始滚动时间 const Calendar = () => { const ref = useRef<any>(); const [printResolve, setPrintResolve] = useState<{ val: number; resolve: (value: any) => void; }>(); const [currentScrollTime, setCurrentScrollTime] = useState(INITIAL_SCROLL_TIME); const handlePrint = useReactToPrint({ content: () => ref?.current?.calendar?.el as any, onBeforeGetContent: () => new Promise((resolve) => { // 获取当前日历的滚动时间 const currentScroll = ref.current.calendar.getScrollTime(); setCurrentScrollTime(currentScroll); setPrintResolve({ val: 1, resolve }); }), onAfterPrint: () => { // 打印完成后恢复初始滚动时间 setCurrentScrollTime(INITIAL_SCROLL_TIME); setPrintResolve(undefined); }, }) as () => void; useEffect(() => { printResolve?.resolve?.(undefined); }, [printResolve]); return ( <FullCalendar customButtons={{ print: { text: 'Print', click: handlePrint }, }} ref={ref} initialView="timeGridWeek" eventSources={events} scrollTime={currentScrollTime} // 使用动态的滚动时间 headerToolbar={printResolve ? undefined : { end: 'print' }} /> ); }; export default Calendar;
关键说明
getScrollTime():FullCalendar提供的方法,用于获取当前日历视图滚动到的时间点- 动态修改
scrollTime:打印前将该属性设置为当前滚动时间,让日历视图自动滚动到用户当前看到的位置,此时打印的内容就是当前视图区域 - 恢复初始设置:打印完成后把
scrollTime改回初始值,保证日常使用的视图不受影响
内容的提问来源于stack exchange,提问作者TwoShorts
相关产品推荐
相关产品推荐

