如何在react-big-calendar默认日视图右侧添加月历侧边栏
实现react-big-calendar日视图+右侧月历侧边栏
核心思路
直接实例化两个react-big-calendar组件,一个作为主区域的日视图,另一个作为侧边栏的月视图,通过共享状态同步两者的显示日期,再用CSS布局实现左右排列。
具体实现步骤
1. 基础布局与状态设置
用flex布局容器包裹两个日历组件,给月历侧边栏设置固定宽度。同时维护一个currentDate状态,用于同步两个日历的显示日期。
2. 同步日期交互
给月历组件绑定onSelectSlot事件,当点击月历中的日期时,更新currentDate,让日视图自动跳转到选中的日期。
3. 样式优化
调整月历侧边栏的样式,比如缩小尺寸、添加边框、调整内边距,让它适配侧边栏的展示需求。
代码示例
import React, { useState } from 'react'; import { Calendar, momentLocalizer } from 'react-big-calendar'; import moment from 'moment'; import 'react-big-calendar/lib/css/react-big-calendar.css'; const localizer = momentLocalizer(moment); const CalendarApp = () => { // 初始化当前日期为今天 const [currentDate, setCurrentDate] = useState(new Date()); // 模拟事件数据 const events = [ { title: '会议', start: new Date(new Date().setHours(10, 0, 0)), end: new Date(new Date().setHours(11, 0, 0)), }, { title: '午餐', start: new Date(new Date().setHours(12, 0, 0)), end: new Date(new Date().setHours(13, 0, 0)), }, ]; // 月历点击日期时同步到日视图 const handleMonthDateSelect = ({ start }) => { setCurrentDate(start); }; return ( <div style={{ display: 'flex', gap: '20px', padding: '20px' }}> {/* 主区域:日视图 */} <div style={{ flex: 1 }}> <Calendar localizer={localizer} events={events} startAccessor="start" endAccessor="end" view="day" date={currentDate} style={{ height: '80vh' }} /> </div> {/* 侧边栏:月视图 */} <div style={{ width: '300px', border: '1px solid #eee', padding: '10px' }}> <h3>月历导航</h3> <Calendar localizer={localizer} events={events} startAccessor="start" endAccessor="end" view="month" date={currentDate} onSelectSlot={handleMonthDateSelect} style={{ height: '70vh' }} // 可选:隐藏月历的工具栏,只保留日历主体 toolbar={false} /> </div> </div> ); }; export default CalendarApp;
额外优化点
- 如果不需要月历显示事件,可以给月历组件的
events传空数组,只保留日期导航功能。 - 自定义月历的样式,比如缩小日期单元格的字体、调整行高,让它更紧凑。
- 给日视图添加
onNavigate事件,当日视图切换日期时,同步更新月历的选中日期。
内容的提问来源于stack exchange,提问作者Jennifer De Goede
相关产品推荐
相关产品推荐

