教程 chartjs tutorial

在 React 中使用

在 React 中,可以通过函数组件配合 useEffect 和 useRef 钩子来使用 Chart.js,实现图表的动态渲染和生命周期管理。

下面示例是一个简单的 React 组件,展示如何初始化和销毁 Chart.js 图表。

jsx
import React, { useRef, useEffect } from "react";
import Chart from "chart.js/auto";

export default function MyChart() {
  const chartRef = useRef(null);
  let chartInstance = null;

  useEffect(() => {
    const ctx = chartRef.current.getContext("2d");
    chartInstance = new Chart(ctx, {
      type: "bar",
      data: {
        labels: ["一月", "二月", "三月", "四月", "五月"],
        datasets: [
          {
            label: "销售额",
            data: [12, 19, 3, 5, 2],
            backgroundColor: "rgba(75, 192, 192, 0.7)",
          },
        ],
      },
      options: {
        responsive: true,
        plugins: {
          legend: { display: true },
        },
      },
    });

    return () => {
      chartInstance.destroy();
    };
  }, []);

  return <canvas ref={chartRef} width={600} height={400} />;
}
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>React 中使用 Chart.js 示例</title> <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js&quot;&gt;&lt;/script&gt; <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js&quot;&gt;&lt;/script&gt; <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 700px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  margin: 1rem auto;
}

</style> </head>

<body> <div id="root"></div> <script type="text/javascript"> (function () { const { useRef, useEffect } = React;

  function MyChart() {
    const chartRef = useRef(null);
    let chartInstance = null;

    useEffect(() =&gt; {
      const ctx = chartRef.current.getContext('2d');
      chartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['一月', '二月', '三月', '四月', '五月'],
          datasets: [{
            label: '销售额',
            data: [12, 19, 3, 5, 2],
            backgroundColor: 'rgba(75, 192, 192, 0.7)'
          }]
        },
        options: {
          responsive: true,
          plugins: {
            legend: { display: true }
          }
        }
      });

      return () =&gt; {
        chartInstance.destroy();
      };
    }, []);

    return React.createElement('canvas', { ref: chartRef, width: 600, height: 400 });
  }

  ReactDOM.createRoot(document.getElementById('root')).render(React.createElement(MyChart));
})();

</script> </body>

</html>