如何在 react-chartjs-2 中使用 chartjs-plugin-trendline

问题描述

我想在我的折线图中添加“趋势”线。我正在使用 react-chartjs-2 在我的网站上绘制图表。代码如下:

import { Line } from 'react-chartjs-2';
import trendlineLinear from 'chartjs-plugin-trendline';

const PatientInfectionChart = ({ data,labels }) => {
  const datasets = [
    {
      data: data.totalInfected,backgroundColor: 'rgb(233,85,0)',borderColor: 'rgba(233,0.7)',label: 'Today Infected',},{
      data: data.todayRecovered,backgroundColor: 'rgb(23,198,113)',borderColor: 'rgba(23,113,label: 'Today Recovered',trendlineLinear: {
        style: 'rgb(23,linestyle: 'dotted',width: 2,];
  return (
    <Line
      data={{ datasets,labels }}
      plugins={[trendlineLinear]}
      options={{
        maintainAspectRatio: false,scales: {
          y: {
            beginAtZero: true,}}
    />
  );
};

export default PatientInfectionChart;

但是,我收到以下错误

Uncaught TypeError: Cannot read property 'ctx' of undefined
    at Object.afterDraw (chartjs-plugin-trendline.js:23)
    at callback (helpers.segment.js:89)
    at PluginService._notify (chart.esm.js:4737)
    at PluginService.notify (chart.esm.js:4724)
    at Chart.notifyPlugins (chart.esm.js:5788)
    at Chart.draw (chart.esm.js:5537)
    at chart.esm.js:66
    at Map.forEach (<anonymous>)
    at Animator._update (chart.esm.js:44)
    at chart.esm.js:34

我该如何解决这个问题?

解决方法

趋势线插件需要 chart.js 版本 2,react chart.js 使用版本 3,所以你需要降级 react-chartjs

命令:

纱线移除 react-chartjs-2

纱线添加 [email protected]