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

React Big Calendar 错位求助:组件显示偏左而非居中

React Big Calendar 组件错位(左对齐而非居中)问题解决

我在项目中使用React Big Calendar组件时遇到布局错位问题:日历显示在页面左侧,无法居中,和预期的居中布局不符。

问题表现

  • 实际效果:日历组件左对齐,内容集中在页面左侧区域
  • 预期效果:日历组件水平居中,布局规整

我的代码

import { Calendar, dayjsLocalizer } from 'react-big-calendar'
import dayjs from 'dayjs'
import { useState } from 'react';

const Tryyy = () => {
    const localizer = dayjsLocalizer(dayjs)

    const [eventList] = useState([
        {
            start: new Date(2025, 1, 25),
            end: new Date(2025, 1, 25),
            type: 'leave',
        },
    ]);

    return (
        <div>
            <Calendar
                localizer={localizer}
                events={eventList}
                startAccessor="start"
                endAccessor="end"
                style={{ height: 500 }}
            />
        </div>
    )
}

export default Tryyy

解决方法

  1. 导入组件默认样式
    React Big Calendar依赖官方提供的CSS来处理基础布局,缺失样式会导致布局错乱。在代码中添加样式导入:
import 'react-big-calendar/lib/css/react-big-calendar.css';
  1. 设置父容器居中样式
    给包裹Calendar的div添加水平居中的样式,确保组件在页面中居中显示:
return (
    <div style={{ maxWidth: '1200px', margin: '0 auto', padding: '0 1rem' }}>
        <Calendar
            localizer={localizer}
            events={eventList}
            startAccessor="start"
            endAccessor="end"
            style={{ height: 500 }}
        />
    </div>
)

原理说明

  • 导入官方CSS后,组件会获得正确的布局结构,避免元素错位
  • 父容器的margin: 0 auto配合maxWidth可以让日历在不同屏幕尺寸下保持居中,同时限制最大宽度避免内容过度拉伸

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:03:13