在我的ReactJS App的新任务中实现ChartJS的问题,请让我知道我错在哪里



我想在我的react应用程序中上传一个图表,但是当我使用这个Barchar。JSX组件(使用js没有任何改变)它显示控制台以下错误(在图像中)

import React from "react";
import { Bar, Chart } from "react-chartjs-2";
import {Chart as ChartJS, BarElement } from 'chart.js';
ChartJS.register(BarElement)
const BarChart = () => {
var data = {
labels: ['RCB', 'MI', 'RR', 'SRH', 'CSK', 'KXIP', 'DD', 'DCH', 'GL', 'RPS', 'KKR'],
datasets: [{
label: '# of toss wins',
data: [70, 85, 63, 35, 66, 68, 72, 43, 15, 6, 78],
backgroungColor: ['red', 'lightblue', 'pink', 'orange', 'yellow', 'gold', 'blue', 'black', 'gold', 'voilet', 'purple' ],
borderWidth: 1
}]
};
var options = {
maintainAspectRatio: false,
scales: {
y:{
beginAtZero: true
}
},        
};
return (
<div>
<Bar

data= {data} 
height={400}
width={600}
options={options}
/>
</div>
)
};
export default BarChart ;

这是因为您尝试使用treeshaking,但只导入和注册了条形图的元素,而chart.js需要更多。

为方便使用,您最好更改

import {Chart as ChartJS, BarElement } from 'chart.js';
ChartJS.register(BarElement)

为:

import 'chart.js/auto'

如果你真的想使用treeshaking,你应该查看文档,导入并注册你正在使用的所有内容:https://www.chartjs.org/docs/3.7.1/getting-started/integration.html bundlers-webpack-rollup-etc

SO BASSICALLY MISTAKE WHICH I DID WAS I DIDN'T IMPORT  THIS BARCHART IN APPJS.CORRECT CCODE WILL BE LIKE THIS (FOR BARCHART.JSX) YOU CAN CHANGE IN IT MANY THINGS.

import React from "react";
import { Bar } from "react-chartjs-2";
import 'chart.js/auto'

const BarChart =() => {
return <div>
<Bar 
options={{

scales: {
y: {
beginAtZero: true
}
}
}}
data ={{
labels: ['RCB', 'MI', 'RR', 'SRH', 'CSK', 'KXIP', 'DD', 'DCH', 'GL', 'RPS', 'KKR'],
datasets: [{
label: '# of  toss wins',
data: [70, 85, 63, 35, 66, 68, 72, 43, 15, 6, 78],
backgroundColor: ['red', 'Blue', '#ff64dc', '#fc7404', 'yellow', 'red', '#000080', 'silver', 'gold', '#9400d3', 'purple' ],
borderColor:['black'],
borderWidth: 1
},
{
label: '# of match wins',
data: [73, 92, 63, 42, 79, 70, 62, 29, 13, 10, 77],
backgroundColor: ['#C9920E', 'Blue', '#ff64dc', '#fc7404', 'yellow', 'lightgrey', '#000080', 'silver', 'gold', '#9400d3', 'purple' ],
borderColor:['black'],
borderWidth: 1
}
]

}}
/></div>
};  
export default BarChart ;

相关内容