在我的ReactJS应用程序新任务中实现ChartJS时出现问题,请告知我错误的地方

iezvtpos  于 2022-11-07  发布在  Chart.js
关注(0)|答案(2)|浏览(331)

我想上传一个图表在我的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 ;
9nvpjoqh

9nvpjoqh1#

这是因为您尝试使用treeshaking,但只导入和注册了bar元素,而chart.js需要更多的元素。
为了便于使用,您最好进行更改

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

ChartJS.register(BarElement)

转换为:

import 'chart.js/auto'

如果你真的想使用shaking,你应该看看文档,导入并注册你正在使用的一切:https://www.chartjs.org/docs/3.7.1/getting-started/integration.html#bundlers-webpack-rollup-etc

ocebsuys

ocebsuys2#

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 ;

相关问题