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

求助:MUI X Line Chart 无法实现响应式显示问题

MUI X Line Chart 响应式显示问题解决方法

你的LineChart无法实现响应式的核心原因是硬编码了固定宽度width={600},这会让图表尺寸固定,无法随父容器的布局变化自适应调整。

解决步骤:

  • 移除LineChart组件上的width属性,让图表自动继承父容器的宽度
  • 保留height属性(或根据需求动态调整),确保图表高度稳定
  • 你的父容器已经用Tailwind的响应式网格类做了布局适配,只要图表不固定宽度就能跟着容器自适应

修改后的代码示例:

<div className="grid sm:col-span-full lg:grid-cols-2 lg:grid-rows-3 lg:gap-8">
  <div className="overflow:hidden">
    <LineChart
      xAxis={[
        {
          id: "Years",
          data: years,
          scaleType: "utc",
          valueFormatter: (date) =>
            date.toLocaleDateString("en-US", {
              year: "numeric",
              month: "short",
            }),
        },
      ]}
      series={[
        {
          id: "France",
          label: "Quarter",
          data: FranceGDPperCapita,
          stack: "total",
          area: true,
          showMark: true,
        },
      ]}
      height={400}
      margin={{ left: 70 }}
    />
  </div>
</div>

进阶响应式优化(可选)

如果需要针对不同屏幕尺寸调整图表的高度、边距等参数,可以结合MUI的主题和媒体查询钩子:

import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';

// 组件内部逻辑
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

// 渲染LineChart时动态传参
<LineChart
  // 其他属性...
  height={isMobile ? 300 : 400}
  margin={{ left: isMobile ? 50 : 70 }}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 17:06:25