使用react-chartjs-2创建折线图的引用

bweufnob  于 2023-06-05  发布在  Chart.js
关注(0)|答案(1)|浏览(214)

我试图创建一个引用到我正在用chart.jsreact-chartjs-2构建的图表。
下面是我试图创建ref指定类型的行:const chartRef = useRef<Line>(null);
这是我得到的错误:

'Line' refers to a value, but is being used as a type here. Did you mean 'typeof Line'?

我发现了下面的documentation,但由于我是TypeScript的新手,我还不知道如何解释它。下面是我使用的完整代码:

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

import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
} from "chart.js";
import { useRef } from "react";

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

export const data = {
  labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
  datasets: [
    {
      label: "First dataset",
      data: [33, 53, 85, 41, 44, 65],
      fill: true,
      backgroundColor: "rgba(75,192,192,0.2)",
      borderColor: "rgba(75,192,192,1)"
    },
    {
      label: "Second dataset",
      data: [33, 25, 35, 51, 54, 76],
      fill: false,
      borderColor: "#742774"
    }
  ]
};

export default function App() {
  const chartRef = useRef<Line>(null);

  return (
    <div className="App">
      <h1>This is a chart.</h1>
      <Line data={data} ref={chartRef} />
    </div>
  );
}

你能给我指出正确的方向吗?谢谢!

rhfm7lfc

rhfm7lfc1#

我对ChartJS不是很熟悉,但是当我将现有的代码从const chartRef = useRef<Line>(null);更改为const chartRef = useRef<'line'>(null);(根据文档)时,linter给了我一个更好的主意,让我知道需要修复什么(在ref上)。

在您的案例中:

export function App() {
  const chartRef = useRef<ChartJS<"line", number[], string>>(null);

  return (
    <div className="App">
      <h1>This is a chart.</h1>
      <Line data={data} ref={chartRef} />
    </div>
  );
}

Working CodeSandbox

相关问题