Vin*_*e M 37 reactjs chart.js react-chartjs-2
我正在开发一个 React 应用程序,我想在其中显示图表。我尝试使用react-chartjs-2,但我找不到让它工作的方法。当我尝试使用 Pie 组件时,出现错误:Error: "arc" is not a registered element.
我做了一个非常简单的反应应用程序:
这是我的 package.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"chart.js": "^3.6.0",
"cra-template": "1.1.2",
"react": "^17.0.2",
"react-chartjs-2": "^4.0.0",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 App.js 文件:
import React from 'react'
import { Pie } from 'react-chartjs-2'
const BarChart = () => {
return (
<Pie
data={{
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
{
label: '# of votes',
data: [12, 19, 3, 5, 2, 3],
},
],
}}
height={400}
width={600}
/>
)
}
const App = () => {
return (
<div>
<BarChart />
</div>
)
}
export default App
Run Code Online (Sandbox Code Playgroud)
我还尝试遵循此教程:https://www.youtube.com/watch?v =c_9c5zkfQ3Y&ab_channel=WornOffKeys
他使用旧版本的 charJs 和react-chartjs-2。当我替换我的react-chartjs-2和chartjs版本时,它可以在我的应用程序上运行。
"chart.js": "^2.9.4",
"react-chartjs-2": "^2.10.0",
Run Code Online (Sandbox Code Playgroud)
有谁知道如何解决我遇到的错误(无需保留旧版本的图表Js和react-chartjs-2)?
Lee*_*lee 67
自 Chart.js V3 起,Chart.js 就可进行 Treeshakable,因此您需要导入并注册您正在使用的所有元素。
import {Chart, ArcElement} from 'chart.js'
Chart.register(ArcElement);
Run Code Online (Sandbox Code Playgroud)
对于所有可用的导入和注册组件的方法,您可以阅读普通的 Chart.js文档
小智 21
I ran into the same issue earlier, found the solution on react-chartjs-2 documentation page: https://react-chartjs-2.netlify.app/docs/migration-to-v4#tree-shaking
import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';
<Chart type='line' data={chartData} />
Run Code Online (Sandbox Code Playgroud)
All you have to do is to add this line import 'chart.js/auto';
| 归档时间: |
|
| 查看次数: |
37249 次 |
| 最近记录: |