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

React项目中Doughnut/Pie图表无法显示,仅Line/Bar图表正常

解决React中react-chartjs-2 Doughnut/Pie图表无法渲染的问题

我之前也碰到过一模一样的问题!Bar和Line图表正常显示,但Doughnut、Pie只露出空白的canvas区域,大概率是版本兼容问题或者没满足Chart.js v3+的配置/注册要求,咱们一步步来解决:

1. 先确认依赖版本匹配

react-chartjs-2和chart.js的版本必须严格对应,版本不匹配是这类问题的高发原因。比如react-chartjs-2 v4.x必须搭配chart.js v3.x;v5.x则需要chart.js v4.x。

先卸载现有依赖,重装兼容的版本(这里以常用的v4+v3组合为例):

npm uninstall react-chartjs-2 chart.js
npm install react-chartjs-2@^4.3.0 chart.js@^3.9.1

2. 修正图表尺寸的配置方式

你代码里直接在options里写width:"400", height:"400"是错误的——在Chart.js v3+中,图表尺寸应该通过外层容器的CSS控制,而不是options参数,否则会和responsive: true的设置冲突,导致图表无法正确渲染。

修改后的代码如下:

import React from 'react';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Doughnut } from 'react-chartjs-2';

// 注册Doughnut/Pie图表必需的元素
ChartJS.register(ArcElement, Tooltip, Legend);

const state = {
 labels: ['January', 'February', 'March', 'April', 'May'],
 datasets: [
 {
 label: 'Rainfall',
 backgroundColor: [
 '#B21F00', '#C9DE00', '#2FDE00', '#00A6B4', '#6800B4'
 ],
 hoverBackgroundColor: [
 '#501800', '#4B5000', '#175000', '#003350', '#35014F'
 ],
 data: [65, 59, 80, 81, 56]
 }
 ]
}

export default class App extends React.Component {
 render() {
 return (
 // 用外层容器控制尺寸
 <div style={{ width: '400px', height: '400px' }}>
 <Doughnut 
  data={state} 
  options={{ 
    responsive: true, 
    maintainAspectRatio: true, 
    title:{ 
      display:true, 
      text:'Average Rainfall per month', 
      fontSize:20 
    }, 
    legend:{ 
      display:true, 
      position:'right' 
    } 
  }} 
 />
 </div>
 );
 }
}

3. 手动注册ChartJS必需的组件

Chart.js v3+采用了模块化设计,Pie/Doughnut这类环形/饼形图表依赖ArcElement,而提示框、图例需要Tooltip和Legend组件。虽然react-chartjs-2会自动注册一部分,但有时候会出现遗漏,手动注册能确保万无一失。

上面的代码已经加上了注册代码:

ChartJS.register(ArcElement, Tooltip, Legend);

按照这三个步骤操作后,你的Doughnut和Pie图表应该就能正常显示了!我当初就是因为没注册ArcElement,折腾了好久才找到原因😂

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 21:52:49