使用离子6与chartJSReact

c8ib6hqw  于 2022-11-29  发布在  Chart.js
关注(0)|答案(1)|浏览(98)

我试图渲染一个图形与离子React,但我不断得到错误,如:
未捕获的错误:画布已在使用中。必须先销毁ID为“0”的图表,然后才能重用ID为“”的画布。

import { Bar } from "react-chartjs-2";

const Graph: React.FC = (props) => {
  const data = {
    labels: ["Billable", "Non Billable"],
    datasets: [
      {
        label: "Billable Vs. Non Billable",
        backgroundColor: ["#36a2eb", "rgba(255,99,132,0.2)"],
        borderColor: "rgba(255,99,132,1)",
        borderWidth: 1,
        hoverBackgroundColor: "rgba(255,99,132,0.4)",
        hoverBorderColor: "rgba(255,99,132,1)",
        data: [65, 59],
      },
    ],
  };

  return (
    <div>
      <h2>bar example</h2>

      <Bar
        data={data}
        width={100}
        height={50}
        options={{ maintainAspectRatio: false }}
      />
    </div>
  );
};

export default Graph;

有人知道怎么解决吗?

vulvrdjw

vulvrdjw1#

我已经找到了一个解决方案,从这个post信用到@TechMaze
我必须从chart.js导入CategoryScale,从chart.js/auto导入Chart
看起来来自X1 M5 N1 X的X1 M4 N1 X不能解决这个问题(!)

import { Bar } from "react-chartjs-2";
import { CategoryScale } from "chart.js";
import { Chart as ChartJS } from "chart.js/auto";
import {
  IonTitle,
  useIonViewWillEnter,
  useIonViewWillLeave,
} from "@ionic/react";

const Graph: React.FC = () => {
  useIonViewWillEnter(() => {
    ChartJS.register(CategoryScale);
  }, []);

  useIonViewWillLeave(() => {
    ChartJS.unregister(CategoryScale);
  }, []);

  const data = {
    labels: ["Billable", "Non Billable"],
    datasets: [
      {
        label: "Billable Vs. Non Billable",
        backgroundColor: ["#36a2eb", "rgba(255,99,132,0.2)"],
        borderColor: "rgba(255,99,132,1)",
        borderWidth: 1,
        hoverBackgroundColor: "rgba(255,99,132,0.4)",
        hoverBorderColor: "rgba(255,99,132,1)",
        data: [65, 59],
      },
    ],
  };

  return (
    <>
      <IonTitle>Bar Example</IonTitle>
      <Bar data={data} />
    </>
  );
};

export default Graph;

相关问题