我在react组件中有一个画布。我使用了react refs来访问节点,并添加了destroy((方法
TypeError: canvasRef.current.destroy is not a function
我们如何使用react refs访问节点(画布(并销毁该画布?
import React, { useEffect } from "react";
import Chart from "chart.js";
export default function WaterFallChart() {
const canvasRef = React.useRef();
if (canvasRef.current) {
canvasRef.current.destroy();
}
return (
<React.Fragment>
<div className="canvasParentDiv">
<canvas ref={canvasRef} />
</div>
</React.Fragment>
);
}
以下是我更改的部分
export default function WaterFallChart(props) {
const canvasRef = React.useRef();
useEffect(() => {
const chart = new Chart(canvasRef.current, {
type: "bar",
data: {
labels: ["sun", "mon", "tue", "wed", "thurs", "fri"],
datasets: [
{
label: "Good",
data: props.data,
}
]
},
});
return () => {
chart.destroy();
};
}, [props.data]);
return (
<div className="canvasParentDiv">
<canvas ref={canvasRef} />
</div>
);
}
destroy
不是HTMLCanvasElement上的一个方法,但如果您只想从DOM中删除<canvas>
,则无需担心。当WaterFallChart组件卸载时,React将自动从DOM中删除<canvas>
元素。
如果您使用的是Chart.js,那么destroy
是Chart对象上的方法,而不是画布上的方法。您可能仍然会在效果的清理函数中调用它,而不是在组件主体中。
export default function WaterFallChart() {
const canvasRef = React.useRef();
useEffect(() => {
// Code here will run after canvasRef.current has
// been populated with the HTMLCanvasElement, this
// is where you would create the Chart object.
const chart = new Chart(canvasRef.current, ...);
// You probably don't want to destroy the chart
// until the component is unmounting, so you would
// return it as the effect's cleanup function:
return () => {
chart.destroy();
}
}, [])
// ...
}