React使用react-chartjs-2渲染柱状图报错“category is not a registered scale”
问题原因
Chart.js 3.x 及配套的 react-chartjs-2 4.x 版本默认采用按需注册机制,不会自动导入所有内置的比例尺、图表类型、插件等资源。你当前代码用到了category类别比例尺、linear线性比例尺、Bar柱状图元素,但没有提前完成注册,因此触发报错。
解决方案
方案1:全量注册(操作最简,适合快速开发)
直接在组件文件顶部导入所有 Chart.js 内置资源并注册即可,修改后的完整代码如下:
import React from "react"; import { Bar } from "react-chartjs-2"; // 新增全量导入和注册逻辑 import { Chart as ChartJS, registerables } from 'chart.js'; ChartJS.register(...registerables); const BarComponent = () => { return ( <> <Bar width={600} height={400} data={{ labels: ["January", "February", "March", "April", "May", "June"], datasets: [ { label: "months", data: [12, 19, 3, 5, 2, 3], backgroundColor: "red", }, ], }} /> </> ); }; export default BarComponent;
方案2:按需注册(打包体积更小,适合生产环境优化)
仅注册当前柱状图用到的资源即可,打包时不会引入未使用的冗余资源,代码如下:
import React from "react"; import { Bar } from "react-chartjs-2"; // 按需导入依赖的资源 import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, } from 'chart.js'; // 注册导入的资源 ChartJS.register( CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend ); const BarComponent = () => { return ( <> <Bar width={600} height={400} data={{ labels: ["January", "February", "March", "April", "May", "June"], datasets: [ { label: "months", data: [12, 19, 3, 5, 2, 3], backgroundColor: "red", }, ], }} /> </> ); }; export default BarComponent;
内容的提问来源于stack exchange,提问作者Pradip Chinta
相关产品推荐
相关产品推荐

