FullCalendar单事件选中样式重置问题:点击新事件还原上一事件
React FullCalendar 实现单选事件标记的可靠方案
在React项目的FullCalendar组件中,通过eventClick给点击事件添加红色边框标记选中状态时,切换点击新事件后上一个选中事件的边框无法自动还原为透明。之前尝试的多选切换、存储ID重置样式、重新获取事件这三种方案均存在缺陷,以下是更可靠的解决思路:
核心方案:用React状态驱动事件样式
通过维护React状态跟踪当前选中的事件ID,结合FullCalendar的eventClassNames属性动态控制事件样式,完全由状态驱动样式变化,避免视觉延迟和性能问题。
具体实现步骤
- 维护选中状态:在组件中定义
selectedEventId状态,存储当前选中事件的唯一ID - 定义样式类:设置默认事件边框为透明,选中事件边框为红色,添加过渡动画优化视觉体验
- 动态绑定样式类:通过
eventClassNames根据事件ID与selectedEventId的匹配关系,决定是否添加选中样式 - 更新选中状态:在
eventClick回调中直接更新selectedEventId为当前点击事件的ID
代码示例
import { useState } from 'react'; import FullCalendar from '@fullcalendar/react'; import dayGridPlugin from '@fullcalendar/daygrid'; const Calendar = () => { const [selectedEventId, setSelectedEventId] = useState(null); // 内联样式定义 const calendarStyles = ` .fc-event { border: 2px solid transparent; transition: border-color 0.2s ease; } .fc-event.selected-event { border-color: red; } `; return ( <> <style>{calendarStyles}</style> <FullCalendar plugins={[dayGridPlugin]} events={[ { id: 'event-1', title: '会议', start: '2024-06-10' }, { id: 'event-2', title: '周报', start: '2024-06-12' } ]} // 动态分配样式类 eventClassNames={({ event }) => event.id === selectedEventId ? 'selected-event' : '' } // 点击事件更新选中状态 eventClick={({ event }) => { setSelectedEventId(event.id); }} /> </> ); }; export default Calendar;
方案优势
- 无视觉延迟:React状态更新会触发
eventClassNames重新计算,样式切换同步完成,不会出现短暂多选中的视觉问题 - 性能高效:仅针对当前选中和上一个选中的事件修改样式,无需重新获取所有事件
- 逻辑清晰:状态与样式绑定,符合React数据驱动视图的设计理念
扩展优化
如果需要支持点击空白区域取消选中,可以给日历容器添加点击事件,判断点击目标不属于事件元素时,清空selectedEventId:
// 在FullCalendar外层添加容器 <div onClick={(e) => { if (!e.target.closest('.fc-event')) { setSelectedEventId(null); } }}> <FullCalendar {...props} /> </div>
内容的提问来源于stack exchange,提问作者BalancingComic
相关产品推荐
相关产品推荐

