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

ggl*_*ses 4 javascript typescript reactjs chart.js

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'?
Run Code Online (Sandbox Code Playgroud)

我找到了以下文档,但由于我是 TypeScript 的新手,所以我还不知道如何解释它。这是我正在使用的完整代码:

'Line' refers to a value, but is being used as a type here. Did you mean 'typeof Line'?
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*mez 5

我对 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

工作代码沙箱

  • @cBlaine 我已经有一段时间没有看过这个了,但据我所知,我*认为*是 https://react-chartjs-2.js.org/components/chart for `ChartTypeRegistry` 引导了我到 https://github.com/chartjs/Chart.js/blob/9871aaa2628e47d1b8bf454a3d29b2cb0232b046/types/index.d.ts 获取实际的注册表项。 (4认同)