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

如何在React应用中使用FullCalendar方法?以getEvents()为例

在React中调用FullCalendar的getEvents()等方法

嘿,这事儿其实不难,核心是要先拿到FullCalendar的底层实例,之后就能调用官方文档里的所有方法啦。下面分两种组件类型给你讲具体操作:

1. 函数组件(使用useRef)

首先用React的useRef钩子创建一个引用,把它绑定到FullCalendar组件上,之后通过这个引用获取到Calendar实例:

import { useRef } from 'react';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';

export default function MyCalendar() {
  // 创建ref用于关联FullCalendar组件
  const calendarRef = useRef(null);

  // 定义触发getEvents的方法
  const fetchAllEvents = () => {
    // 获取FullCalendar的底层API实例
    const calendarApi = calendarRef.current.getApi();
    // 调用getEvents()方法拿到所有事件
    const allEvents = calendarApi.getEvents();
    console.log('当前日历所有事件:', allEvents);
  };

  return (
    <div>
      <button onClick={fetchAllEvents}>获取所有日历事件</button>
      <FullCalendar
        ref={calendarRef} // 将ref绑定到FullCalendar组件
        plugins={[dayGridPlugin]}
        initialView="dayGridMonth"
        events={[
          { title: '团队会议', start: new Date() }
        ]}
      />
    </div>
  );
}

2. 类组件(使用createRef)

如果是类组件,用createRef来创建引用,步骤和函数组件类似:

import React from 'react';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';

class MyCalendar extends React.Component {
  constructor(props) {
    super(props);
    // 创建ref
    this.calendarRef = React.createRef();
  }

  fetchAllEvents = () => {
    // 获取底层API实例
    const calendarApi = this.calendarRef.current.getApi();
    // 调用getEvents()方法
    const allEvents = calendarApi.getEvents();
    console.log('当前日历所有事件:', allEvents);
  };

  render() {
    return (
      <div>
        <button onClick={this.fetchAllEvents}>获取所有日历事件</button>
        <FullCalendar
          ref={this.calendarRef}
          plugins={[dayGridPlugin]}
          initialView="dayGridMonth"
          events={[
            { title: '团队会议', start: new Date() }
          ]}
        />
      </div>
    );
  }
}

export default MyCalendar;

关键注意点

  • getApi()是FullCalendar React封装提供的专属方法,用来获取底层的Calendar对象,拿到这个对象后,你就能调用官方文档里的任意方法了,比如addEvent()、removeEvent()、getEventById()等等。
  • 要确保在调用getApi()之前,FullCalendar已经完成渲染,不然calendarRef.current可能是null。所以建议在用户交互(比如按钮点击)或者组件的componentDidMount(类组件)/useEffect(函数组件,依赖项为空数组)里调用这类方法。

内容的提问来源于stack exchange,提问作者VladR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:47:08