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

标签 javascript reactjs typescript

我正在尝试为我正在使用 chart.js 构建的图表创建一个引用和 react-chartjs-2 .

这是我尝试创建指定类型的引用的行: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>
  );
}

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

最佳答案

我不是很熟悉 ChartJS,但是当我从 const chartRef = useRef<Line>(null); 更改您现有的代码时至 const chartRef = useRef<'line'>(null); (根据文档),linter 让我更好地了解需要修复的内容(在 ref 上)。

Linter Error

在你的情况下:

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

关于javascript - 使用 react-chartjs-2 创建对折线图的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72455131/

相关文章:

reactjs - 停止观察reactjs中的文件夹变化

reactjs - 调用 this.setState 后状态没有改变

typescript - 当 DefinitelyTyped 类型定义用于比我想要的版本更新的版本时该怎么办?

javascript - 如何使用ajax将文件发送到另一个php文件后返回文件信息

javascript - 如何在对象的 nodeunit deepEqual 测试中跳过纪元字段?

javascript - 如何将元组字符串提取到数据结构中?

javascript - 创建动态 <div> 并使用编辑 jQuery

reactjs - react - 类型错误 : Cannot read property 'includes' of undefined

angular - 将 SCSS 与 Angular 2/4 结合使用的架构

javascript - typescript + lodash - 找不到模块