这是我的代码:
import dayGridPlugin from "@fullcalendar/daygrid";
import FullCalendar from "@fullcalendar/react";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import { useState, useEffect } from "react";
export default function Calendar(props) {
const [selectedDate, setSelectedDate] = useState(null);
const [view, setView] = useState("dayGridMonth");
const handleDateClick = (info) => {
//window.location.href = route("activity.create", { date: info.dateStr });
setSelectedDate(info.dateStr);
setView("timeGridDay");
};
useEffect(() => {
console.log("Selected Date:", selectedDate);
console.log("View:", view);
}, [selectedDate, view]);
return (
<FullCalendar
plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
initialView={view}
selectable="true"
selectOverlap="false"
height="80vh"
initialDate={selectedDate}
themeSystem="standard"
headerToolbar={{
start: "today prev,next",
center: "title",
end: "dayGridMonth, timeGridWeek, timeGridDay",
}}
dateClick={handleDateClick}
/>
);
}
我知道日期选择有效,因为我已使用警报来验证这一点,我还在控制台中登录了更改,并且日期和视图变量设置正确。在我看来,fullCalendar 只是没有重新渲染。
ref
的
FullCalendar
属性,以便以编程方式使用 CalendarDate 和 View API 方法,如下所示:
import dayGridPlugin from '@fullcalendar/daygrid';
import FullCalendar from '@fullcalendar/react';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { useState, useEffect, useRef } from 'react';
export default function Calendar(props) {
const [selectedDate, setSelectedDate] = useState(null);
const [view, setView] = useState('dayGridMonth');
const calendarRef = useRef(null);
const handleDateClick = (info) => {
//console.log(info);
setSelectedDate(info.dateStr);
setView('timeGridDay');
};
useEffect(() => {
console.log('calendarRef.current:', calendarRef.current);
console.log('Selected Date:', selectedDate);
console.log('View:', view);
if (calendarRef.current) {
calendarRef.current.calendar.changeView(view);
if (selectedDate) {
calendarRef.current.calendar.gotoDate(selectedDate);
}
}
}, [selectedDate, view, calendarRef.current]);
return (
<FullCalendar
ref={calendarRef}
plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
initialView={view}
selectable="true"
selectOverlap="false"
height="80vh"
initialDate={selectedDate}
themeSystem="standard"
headerToolbar={{
start: 'today prev,next',
center: 'title',
end: 'dayGridMonth, timeGridWeek, timeGridDay',
}}
dateClick={handleDateClick}
/>
);
}
您可以查看 this StackBlitz 以获取实时工作示例。