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

React中Bar组件正常,Doughnut等图表组件渲染空白页问题

解决Doughnut/Pie组件渲染空白的问题

核心问题及修复步骤:

  • 依赖版本不兼容:react-chartjs-2 和 chart.js 版本必须严格匹配,比如 react-chartjs-2 v4.x 要求 chart.js v4.x,版本错位会导致非Bar类组件渲染失败。执行以下命令统一版本:

    npm install chart.js@^4 react-chartjs-2@^4
    
  • 饼图组件的颜色配置缺失:Pie/Doughnut 组件建议为每个数据项单独设置背景色,单个颜色在部分版本中可能触发渲染异常。把 backgroundColor 改为数组:

    backgroundColor: [
      "rgba(53, 162, 235, 0.5)",
      "rgba(255, 99, 132, 0.5)",
      "rgba(255, 206, 86, 0.5)",
      "rgba(75, 192, 192, 0.5)"
    ]
    
  • 尺寸属性冲突:移除 Doughnut 组件上的 height 和 width 属性,因为 responsive: true 和 maintainAspectRatio: false 已经让组件自适应容器尺寸,手动设置会导致布局异常。

  • 缺失必要的Chart.js注册项:v4及以上版本的react-chartjs-2需要手动注册饼图所需的元素和插件,Bar组件默认注册了对应元素所以能正常渲染。

修改后的完整代码:

import { Box } from "@chakra-ui/react";
import React from "react";
import { Doughnut } from "react-chartjs-2";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';

// 注册饼图必需的元素和插件
ChartJS.register(ArcElement, Tooltip, Legend);

function Donutchart() {
  return (
    <Box maxH={400} maxWidth={600}>
      <Doughnut
        options={{
          responsive: true,
          plugins: {
            title: {
              display: false,
            },
          },
          maintainAspectRatio: false,
        }}
        data={{
          labels: ["Energy", "envi", "retail", "govt"],
          datasets: [
            {
              label: "Sector",
              data: [54, 36, 12, 45],
              backgroundColor: [
                "rgba(53, 162, 235, 0.5)",
                "rgba(255, 99, 132, 0.5)",
                "rgba(255, 206, 86, 0.5)",
                "rgba(75, 192, 192, 0.5)"
              ],
            },
          ],
        }}
      />
    </Box>
  );
}
export default Donutchart;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:25:19