如何在React-big-calendar当日插槽添加+create-event跳转功能?
在React-big-calendar的当日插槽添加创建事件入口
要实现这个需求,你可以通过自定义日历组件的日期单元格渲染逻辑完成,核心是利用React-big-calendar提供的components属性,替换默认的日期单元格组件,在当日插槽添加自定义的跳转标签。
实现步骤
适配路由跳转
如果项目用React Router管理路由,导入useNavigate钩子;纯前端场景直接用window.location.href即可。自定义日期单元格组件
创建CustomDay组件,判断当前单元格日期是否为当日,若是则添加+create-event标签并绑定跳转逻辑。传入自定义组件到日历
通过components属性将自定义组件传给Calendar,覆盖默认的日期单元格渲染逻辑。
修改后的完整代码
import React from "react"; import { Calendar, momentLocalizer } from "react-big-calendar"; import moment from "moment"; import { useNavigate } from "react-router-dom"; // React Router场景导入 import "react-big-calendar/lib/css/react-big-calendar.css"; const localizer = momentLocalizer(moment); const myEventsList = [ { start: moment("2023-09-23T10:00:00").toDate(), end: moment("2023-09-23T13:00:00").toDate(), title: "Concert", }, { start: moment("2023-09-26T10:00:00").toDate(), end: moment("2023-09-28T13:00:00").toDate(), title: "Music Workshop", }, { start: moment("2023-09-24T10:00:00").toDate(), end: moment("2023-09-24T13:00:00").toDate(), title: "Conference", }, ]; // 自定义日期单元格组件 const CustomDay = ({ date, children, ...props }) => { const navigate = useNavigate(); // React Router跳转钩子 const isToday = moment(date).isSame(moment(), "day"); return ( <div {...props} style={{ position: "relative" }}> {children} {isToday && ( <div style={{ position: "absolute", bottom: 2, right: 2, cursor: "pointer", color: "#165DFF", fontSize: "12px" }} onClick={() => { // React Router跳转方式 navigate("/create-event-page/create-event"); // 纯前端跳转方式(非React Router场景用这个) // window.location.href = "/create-event-page/create-event"; }} > +create-event </div> )} </div> ); }; export default function OrganizerEventCalendar() { const handleSelect = () => { console.log("Hello World"); }; return ( <div> <Calendar localizer={localizer} events={myEventsList} selectable={true} onSelectSlot={handleSelect} startAccessor="start" endAccessor="end" style={{ height: 500 }} views={["month", "week"]} formats={{ weekdayFormat: "dddd" }} className="table-drop-shadow rounded-lg bg-[#F3FAFF] p-3" // 传入自定义组件,覆盖月/周视图的日期单元格 components={{ day: CustomDay, week: { day: CustomDay } }} /> </div> ); }
关键说明
- 日期判断:用
moment(date).isSame(moment(), "day")精准匹配当日日期。 - 样式控制:通过绝对定位把标签放在单元格右下角,避免干扰原有日历内容。
- 多视图兼容:同时配置月视图和周视图的自定义单元格,确保两种视图都能显示创建入口。
内容的提问来源于stack exchange,提问作者Aitezaz Shah
相关产品推荐
相关产品推荐

