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

使用react-chartjs-2绘制的图表在浏览器中无法显示的问题

react-chartjs-2柱状图无报错但无法显示数据

已安装react-chartjs-2依赖,编写了简单柱状图组件,控制台无任何错误提示,但浏览器中无法显示图表数据,仅呈现空白区域。

相关代码

Chart.js 组件代码

import React, {Component} from 'react';
import {Bar } from 'react-chartjs-2';

class Chart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: {
                labels: ['Boston', 'Worcester', 
                'Springfield', 'Lowell', 
                'Cambridge', 'New Bedford'],
                datasets:[
                    {
                        label: 'Population',
                        data: [
                            617594,
                            181045,
                            153060,
                            106519,
                            105162,
                            95072
                        ],
                        backgroundColor:[
                            'rgba(255, 99, 132, 0.6)',
                            'rgba(54, 162, 235, 0.6)',
                            'rgba(255, 206, 86, 0.6)',
                            'rgba(75, 192, 192, 0.6)',
                            'rgba(153, 102, 255, 0.6)',
                            'rgba(255, 159, 64, 0.6)',
                            'rgba(255, 99, 132, 0.6)'
                          ]
                    }
                ]
            }
        }
    }
   
    render() {
        return (
            <div className="chart">
                <Bar
                    data={this.state.chartData}
                    options={{
                        maintainAspectRatio: false
                    }}
                />
            </div>
        )
    }
}

export default Chart;

App.js 代码

import './App.css';
import Chart from './components/Chart';

function App() {
  return (
    <div className="App">
      <Chart />
    </div>
  );
}

export default App;

问题截图

空白的图表容器

解决方法

  • 安装缺失的核心依赖:react-chartjs-2是chart.js的React封装层,必须同时安装chart.js才能正常渲染图表:
    npm install chart.js
    # 或使用 yarn:yarn add chart.js
    
  • 给图表容器设置固定高度:因为配置了maintainAspectRatio: false,图表不会自动计算高度,需要给.chart容器添加高度样式:
    在App.css中添加:
    .chart {
      height: 400px;
      width: 100%;
    }
    
  • 适配高版本组件要求:如果使用的是react-chartjs-2 v4及以上版本,需要额外导入chart.js的自动注册模块,确保图表类型被正确识别:
    在Chart.js文件顶部添加:
    import 'chart.js/auto';
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:25:26