React-ChartJS-2在TypeScript中报错:TypeError: Comp is not a function
解决TypeScript下react-chartjs-2的"TypeError: Comp is not a function"错误
以下是几个可行的解决步骤:
1. 确认依赖版本兼容性
react-chartjs-2 v4.x 要求 chart.js 版本必须是 v3.x,版本不匹配是触发该错误的常见原因。检查你的package.json,确保两者版本兼容:
{ "chart.js": "^3.9.1", "react-chartjs-2": "^4.3.1" }
如果版本不匹配,执行以下命令更新:
npm uninstall chart.js react-chartjs-2 npm install chart.js react-chartjs-2
2. 修正组件的类型定义
避免用any类型模糊定义product_data,明确类型可以避免TS类型推断错误,同时提升代码健壮性:
import { Chart as ChartJS } from 'chart.js/auto'; import { Bar } from 'react-chartjs-2'; // 定义product_data的类型 interface ProductData { pos_count: number; neut_count: number; neg_count: number; } export default function BarChart({ product_data }: { product_data: ProductData }) { const bar_data = { labels: ["Positive Reviews", "Neutral Reviews", "Negative Reviews"], datasets: [{ label: "Number of reviews", data: [product_data.pos_count, product_data.neut_count, product_data.neg_count], backgroundColor: [ 'rgba(75, 192, 192, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(255, 99, 132, 0.2)' ], borderColor: [ 'rgba(75, 192, 192, 1)', 'rgba(255, 206, 86, 1)', 'rgba(255, 99, 132, 1)' ], borderWidth: 0.5, }] }; return <Bar data={bar_data} />; }
3. 清除依赖缓存并重新安装
缓存可能导致TS类型解析异常,执行以下步骤重置依赖:
- 删除
node_modules文件夹和package-lock.json(或yarn.lock) - 执行
npm install重新安装所有依赖
4. 手动注册Chart.js组件(可选)
虽然chart.js/auto会自动注册所有组件,但如果问题仍存在,可以尝试手动注册必要组件:
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from 'chart.js'; import { Bar } from 'react-chartjs-2'; // 手动注册组件 ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend); // 后续组件代码不变...
内容的提问来源于stack exchange,提问作者Revi Bronst
相关产品推荐
相关产品推荐

