React Big Calendar中onEventDrop的event属性TypeScript类型缺失id字段问题
解决React Big Calendar拖拽事件中TypeScript提示id不存在的问题
问题出在React Big Calendar默认的Event类型定义里没有包含id字段,即便你实际传入的事件对象带有id,TypeScript也无法识别。以下是具体解决方法:
自定义扩展事件类型
先基于官方的Event类型扩展出符合你业务的事件类型,补上id属性:import { Event as RBCEvent } from 'react-big-calendar'; // 自定义带id的事件类型 interface MyCalendarEvent extends RBCEvent { id: string | number; }为拖拽日历组件指定自定义类型
使用withDragAndDrop高阶组件时,传入你的自定义事件类型泛型:import { Calendar, withDragAndDrop } from 'react-big-calendar'; // 生成带自定义类型的拖拽日历组件 const DragAndDropCalendar = withDragAndDrop<MyCalendarEvent>(Calendar);修正onEventDrop的参数类型
在事件处理函数中,给EventInteractionArgs传入自定义类型泛型,这样TS就能识别event上的id属性了:import { EventInteractionArgs } from 'react-big-calendar'; const handleEventDrop = ({ event, start, end }: EventInteractionArgs<MyCalendarEvent>) => { // 这里访问event.id不会再报错 console.log('事件ID:', event.id); // 执行你的事件更新逻辑,比如调用接口修改事件时间 };全局扩展(可选)
如果项目中多个组件都用到该日历,可通过全局类型声明统一扩展官方的Event类型,避免每个组件都自定义:
在项目的类型声明文件(比如src/types/react-big-calendar.d.ts)中添加:import 'react-big-calendar'; declare module 'react-big-calendar' { interface Event { id: string | number; } }
内容的提问来源于stack exchange,提问作者abappy
相关产品推荐
相关产品推荐

