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

React项目中react-google-charts图表不渲染仅显示空div求助

排查react-google-charts仅渲染空div的问题

以下是几个常见的疏漏点和解决方法:

1. 未正确导入Chart组件

确保在使用Chart的组件顶部添加导入语句:

import { Chart } from "react-google-charts";

如果省略这一步,React会将<Chart>视为未知HTML标签,最终渲染为空div且无报错。

2. 图表类型与配置不兼容

你使用了ScatterChart,但配置中的curveType: "function"是LineChart专属属性,ScatterChart不支持该配置,这会导致图表静默渲染失败。

解决方法二选一:

  • 改用LineChart(适配你当前的配置和数据):
<Chart
  chartType="LineChart"
  width="80%"
  height="400px"
  data={[
    ["Year", "Sales", "Expenses"],
    ["2004", 1000, 400],
    ["2005", 1170, 460],
    ["2006", 660, 1120],
    ["2008", 1030, 540],
    ["2009", 1000, 400],
    ["2010", 1170, 460],
    ["2011", 660, 1120],
    ["2012", 1030, 540],
  ]}
  options={{
    title: "Company Performance",
    curveType: "function",
    legend: { position: "bottom" },
  }}
/>
  • 保留ScatterChart,调整数据格式(年份改为数值)并移除无效配置:
<Chart
  chartType="ScatterChart"
  width="80%"
  height="400px"
  data={[
    ["Year", "Sales", "Expenses"],
    [2004, 1000, 400],
    [2005, 1170, 460],
    [2006, 660, 1120],
    [2008, 1030, 540],
    [2009, 1000, 400],
    [2010, 1170, 460],
    [2011, 660, 1120],
    [2012, 1030, 540],
  ]}
  options={{
    title: "Company Performance",
    legend: { position: "bottom" },
  }}
/>

3. 容器宽度计算异常

你设置了width="80%",如果父级div没有明确的宽度值,80%会被计算为0,导致图表不可见。

解决方法:

给父容器添加固定宽度或确保父级有明确尺寸:

<div style={{ width: "1000px" }}>
  <Chart {/* ...配置... */} />
</div>

或者将图表宽度改为固定值,比如width="800px"。

4. 版本兼容性问题

如果你的React版本是18,确保react-google-charts是最新版本。执行以下命令更新依赖:

npm update react-google-charts

5. 服务器端渲染(SSR)场景问题

如果在Next.js等SSR框架中使用,需通过动态导入禁用服务器端渲染:

import dynamic from 'next/dynamic';

const Chart = dynamic(() => import('react-google-charts').then(mod => mod.Chart), {
  ssr: false,
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:40:56