我正在使用React,TypeScript和fullCalendar构建应用程序。
我想在我的根组件setState中从fullcalendar组件中选择数据范围。当我选择数据范围时,出现此错误:
TypeError:无法读取未定义的属性“日历”-(第1/2页) TypeError:无法读取null的属性“ getApi”-(第2/2页)
在此行
useEffect(() => {
--> calendarApi = calendarComponentRef.current!.getApi();
});
这是我的代码:
import React, { Dispatch, SetStateAction, useContext, useEffect } from 'react';
import FullCalendar from '@fullcalendar/react';
import interactionPlugin from '@fullcalendar/interaction';
import dayGridPlugin from '@fullcalendar/daygrid';
import { WizardContext } from '../../ReservationWizard/ReservationWizard';
import { EventInput } from '@fullcalendar/core';
type CalendarProps = {
startDate: Date;
endDate: Date;
setStartDate: Dispatch<SetStateAction<Date>>;
setEndDate: Dispatch<SetStateAction<Date>>;
};
const Calendar: React.FC<CalendarProps> = (props) => {
const { changePage, currentPage } = useContext(WizardContext);
const calendarComponentRef = React.createRef<FullCalendar>();
let calendarApi: any;
useEffect(() => {
calendarApi = calendarComponentRef.current!.getApi();
});
const customButtons = {
previous: {
text: '<',
click() {
calendarApi.prev();
},
},
further: {
text: '>',
click() {
calendarApi.next();
},
},
};
const getReservationTime = (event: EventInput) => {
const { start, end } = event;
if (start && end) {
startDate = new Date(start.toString());
endDate = new Date(end.toString());
props.setStartDate(startDate);
props.setEndDate(endDate);
}
};
return (
<div className='calendar-container'>
<FullCalendar
ref={calendarComponentRef}
defaultView='dayGridMonth'
plugins={[interactionPlugin, dayGridPlugin]}
selectable={true}
header={{
left: '',
center: 'previous, title, further',
right: '',
}}
customButtons={customButtons}
dateClick={getReservationTime}
select={getReservationTime}
/>
</div>
);};
export default Calendar;
如果我从getReservationTime()中删除了这部分代码:
props.setStartDate(startDate);
props.setEndDate(endDate);
所有未在setState中设置日期范围的对象都可以正常工作。我可以在日历中选择很多天而不会崩溃的应用程序