You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何访问FullCalendar的Today按钮并添加回调函数?

在React中为FullCalendar的Today按钮添加回调

直接通过原生DOM绑定事件在React环境下失效,原因在于FullCalendar的按钮是动态生成的,React的虚拟DOM机制会导致DOM元素引用不稳定,且直接操作DOM不符合React的开发范式。推荐使用以下两种React友好的方案:

方案一:自定义Today按钮

通过FullCalendar的customButtons配置自定义按钮,替换默认的Today按钮并绑定回调:

import { useRef } from 'react';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';

function CalendarComponent() {
  const calendarRef = useRef(null);

  const handleTodayClick = () => {
    // 获取日历实例,执行内置的today方法
    const calendarApi = calendarRef.current.getApi();
    calendarApi.today();
    // 添加你的自定义逻辑
    console.log('Today按钮被点击,已切换到今日视图');
  };

  return (
    <FullCalendar
      ref={calendarRef}
      plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
      initialView={'dayGridMonth'}
      headerToolbar={{
        start: 'dayGridMonth,timeGridWeek,timeGridDay',
        center: 'title',
        end: 'customToday prev,next', // 用自定义按钮替换默认的today
      }}
      customButtons={{
        customToday: {
          text: 'Today', // 按钮显示文本,和默认一致
          click: handleTodayClick // 绑定点击回调
        }
      }}
      height={'80vh'}
      handleWindowResize={true}
    />
  );
}

export default CalendarComponent;

方案二:监听导航事件

利用FullCalendar的navigate回调,监听点击Today按钮触发的导航行为(direction为current):

import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';

function CalendarComponent() {
  const handleNavigate = ({ date, direction }) => {
    if (direction === 'current') {
      // 点击Today按钮时触发此逻辑
      console.log('Today按钮被点击,当前日期:', date.toLocaleDateString());
      // 添加你的自定义逻辑
    }
  };

  return (
    <FullCalendar
      plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
      initialView={'dayGridMonth'}
      headerToolbar={{
        start: 'dayGridMonth,timeGridWeek,timeGridDay',
        center: 'title',
        end: 'today prev,next', // 保留默认按钮
      }}
      navigate={handleNavigate} // 绑定导航事件回调
      height={'80vh'}
      handleWindowResize={true}
    />
  );
}

export default CalendarComponent;

方案对比

  • 方案一:完全自定义按钮,可灵活修改按钮文本、样式,适合需要自定义按钮外观的场景。
  • 方案二:保留FullCalendar默认按钮样式,仅监听事件,适合无需修改按钮外观的场景。

内容的提问来源于stack exchange,提问作者Rabah Ali Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 20:08:27