首次使用TypeScript与react-chartjs-2遇报错,求问题原因
React-ChartJS-2 折线图组件错误排查求助
首次用TypeScript结合react-chartjs-2开发,已安装react-chartjs-2依赖,但写完折线图组件后遇到无法解决的错误,附上代码及错误说明:
原代码
import React, { useState } from 'react'; import { Line } from 'react-chartjs-2'; import { Chart as ChartJS, LineElement, CategoryScale, LinearScale, PointElement, Legend, Tooltip, Title } from 'chart.js'; ChartJS.register( LineElement, CategoryScale, LinearScale, PointElement, Legend, Tooltip, Title ); function LineChart() { const labels = ['1', '2', '3']; const [data, setData] = useState({ label: labels, datasets: [{ label: 'Data of the selected period', data: [3, 6, 9], backgroundColor: [ 'green' ], borderColor: [ 'grey' ], pointBorderColor: [ 'green' ], borderWidth: 1, fill: true, tension: 0.4 }] }); const options = { plugins: { legend: true }, scales: { y: { min: 0, max: 16 } } }; return <Line data={data} option={options} />; } export default LineChart;
错误原因及修正方案
根据截图显示的类型错误,核心问题有两处:
- 数据结构字段错误:Chart.js要求的X轴标签字段是
labels,原代码写成了label,导致类型不匹配 - 组件属性拼写错误:Line组件的配置属性是
options,原代码拼写为option,组件无法识别该属性
额外优化:backgroundColor、borderColor等如果是统一颜色,无需用数组包裹,直接传入字符串即可,避免不必要的类型警告
修正后的代码
import React, { useState } from 'react'; import { Line } from 'react-chartjs-2'; import { Chart as ChartJS, LineElement, CategoryScale, LinearScale, PointElement, Legend, Tooltip, Title } from 'chart.js'; ChartJS.register( LineElement, CategoryScale, LinearScale, PointElement, Legend, Tooltip, Title ); function LineChart() { const labels = ['1', '2', '3']; const [data, setData] = useState({ // 修正:label → labels labels: labels, datasets: [{ label: 'Data of the selected period', data: [3, 6, 9], // 优化:单一颜色直接用字符串 backgroundColor: 'green', borderColor: 'grey', pointBorderColor: 'green', borderWidth: 1, fill: true, tension: 0.4 }] }); const options = { plugins: { legend: true }, scales: { y: { min: 0, max: 16 } } }; // 修正:option → options return <Line data={data} options={options} />; } export default LineChart;
内容的提问来源于stack exchange,提问作者CodeGirl
相关产品推荐
相关产品推荐

