[英]React Js and Chart Js (Line Chart)
I am trying to add line chart from chart js in react component.我正在尝试在反应组件中添加图表 js 中的折线图。 I have tried the following code but its showing white screen and no errors.
我已经尝试了以下代码,但它显示白屏并且没有错误。 I couldn't figure out what i did wrong.
我无法弄清楚我做错了什么。 I went through chart.js documentation and got confused.
我浏览了 chart.js 文档并感到困惑。 Please give me suggestion how can i display the chart.
请给我建议如何显示图表。 I'm using react-chartjs-2 version 4.0.0 and chart.js version 3.7.0.
我正在使用 react-chartjs-2 版本 4.0.0 和 chart.js 版本 3.7.0。
import React from "react";
import {Line} from 'react-chartjs-2';
const data = {
labels: ['January', 'February', 'March', 'April', 'May'],
datasets: [
{
label: 'Rainfall',
fill: false,
lineTension: 0.5,
backgroundColor: 'rgba(75,192,192,1)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 2,
data: [65, 59, 80, 81, 56]
}
]
}
const config = {
type: 'line',
data: data,
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Line Chart'
}
}
},
};
const SavingsChart = () => {
return (
<Line
data={data}
options={config}
/>
);
};
export default SavingsChart;
You can try to add this line in the beginning of your file, it seems to fix this issue: import Chart from "chart.js/auto";
您可以尝试在文件开头添加这一行,它似乎解决了这个问题:
import Chart from "chart.js/auto";
You should register the chart from chart.js
您应该从
chart.js
注册图表
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend);
You could create the chart in the render()
method.您可以在
render()
方法中创建图表。
render() {
return (
<Line
data={this.state.data}
options={this.state.options}
/>
);
}
Please take a look at the following StackBlitz and see how it works with your amended code.请查看以下StackBlitz并了解它如何与您修改的代码一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.