You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中使用useRef绑定react-chartjs-2图表时类型不匹配问题

解决react-chartjs-2中Ref类型不匹配的问题

问题原因

你遇到的类型错误,是因为useRef指定的类型和Line组件期望的Ref类型不匹配:

  • 你用了chart.js核心库的ChartJS类型,但react-chartjs-2的组件(比如Line)对应的实例类型是该库自己导出的Chart,并且需要明确指定图表类型(比如'line')。

修复步骤

  1. 修正ref的类型定义
    将chartRef的泛型参数从ChartJS改为Chart<'line'>,同时允许值为null:

    const chartRef = useRef<Chart<'line'> | null>(null);
    
  2. 确保类型导入正确
    确认你从react-chartjs-2导入的Chart是正确的类型来源,而不是chart.js的ChartJS。

修改后的完整代码

import { useState, useRef, MouseEvent} from 'react';
declare const Data: { mark: unknown }[];
import { Chart, Line } from 'react-chartjs-2'; // 这里的Chart是react-chartjs-2导出的类型
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { getElementAtEvent } from 'react-chartjs-2/dist/utils';


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


export default function App() {
  const [chartData, setChartData] = useState({
    labels: Data.map(item => item.mark), 
    datasets: [
      {
        label: 'Marks',
        data: Data.map(item => item.mark),
        backgroundColor: '#2a71d0',
        borderColor: 'black',
        borderWidth: 2
      }
    ]
  });
  // 关键修改:指定Chart的类型为'line',并允许null
  const chartRef = useRef<Chart<'line'> | null>(null);

  const onclick = (e:MouseEvent<HTMLCanvasElement>) => {
    if (chartRef.current) {
      console.log(getElementAtEvent(chartRef.current,e))
    }
  }
  return (
    <div className='PerformanceChart'>
      <Line ref={chartRef} data={chartData} onClick={onclick} />
    </div>
  );
}

针对饼图的扩展

如果是饼图(Pie组件),只需要把类型改成Chart<'pie'>即可:

const pieChartRef = useRef<Chart<'pie'> | null>(null);

内容的提问来源于stack exchange,提问作者magicrap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:10:22