我试图用离子反应渲染一个图形,但我不断得到错误,如:
未捕获错误:画布已在使用中。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;
有人知道怎么解吗?
我找到了一个解决方案,这要归功于@TechMaze。
我必须从chart.js
中导入CategoryScale
,从chart.js/auto
中导入Chart
。
似乎Chart
从chart.js
不能解决这个问题(!)
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;