如何使用 ref 访问和销毁 canvas?

How to access and destroy the canvas using ref?

我在反应组件中有一个 canvas。我已经使用 react refs 来访问节点并向其添加了 destroy() 方法。相反,我得到一个错误

TypeError: canvasRef.current.destroy is not a function

我们如何使用 React 引用访问节点 (canvas) 并销毁那个 canvas?

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, then destroy is a method on the Chart object,则不是 canvas。您仍然可能会在效果的清理函数中调用它,而不是在组件主体中。

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();
    }
  }, [])

  // ...
}