reactjs - 在 react-chartjs-2 和 typescript 中使用 chart js 选项
我正在尝试在 react-chartjs 的圆环图中使用一个插件。为了使用这个插件 (https://www.npmjs.com/package/@scottalan/chartjs-plugin-doughnutlabel),我必须向组件传递选项。但是当我尝试传递选项时,我收到一个类型错误
Type '{ doughnutlabel: { labels: { text: string; font: { size: string; family: string; style: string; weight: string; }; color: string; }[]; }; }' is not assignable to type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
Object literal may only specify known properties, and 'doughnutlabel' does not exist in type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
我最好的猜测是,将我的 options 分配给 ChartOptions 是错误的类型,因为即使不尝试使用插件,使用 const options: ChartOptions={} 也会出现相同的错误事件。我的完整代码如下,任何帮助都将不胜感激。
import React, { useEffect, ReactNode, Component } from "react"
import { Chart, ChartOptions, registerables } from 'chart.js'
import { Doughnut } from 'react-chartjs-2';
Chart.register(...registerables);
const MyDoughnut = (props: ComponentProps) => {
const renderChart = (percents: number[]) => {
const data = {
datasets: [{
label: 'Progress',
data: percents,
backgroundColor: [
'rgb(255, 99, 132)',
'transparent',
],
hoverOffset: 4,
cutout: "75%",
radius: "100%"
}]
}
const options: ChartOptions = {
responsive: true,
legend: {
display: false,
position: 'top',
},
title: {
display: true,
fontSize: 20,
text: 'My Title'
},
plugins: {
doughnutlabel: {
labels: [
{
text: "Foo",
font: {
size: '60',
family: 'Arial, Helvetica, sans-serif',
style: 'italic',
weight: 'bold'
},
color: '#bc2c1a'
}
]
}
}
}
return <Doughnut options={options} data={data}></Doughnut>
}
const render = (): ReactNode => {
// const percents = props.args["percents"]
const percents = [76, 24];
return (
<span>
{renderChart(percents)}
</span>
)
}
return <div>{render()}</div>
};
我正在使用 react-chartjs-2 版本 4.0.0 和 react 版本 17.0.2。
答案#1
类型从 chart.js 导出
import type { ChartData, ChartOptions } from 'chart.js';
interface DoughnutProps {
options: ChartOptions<'doughnut'>;
data: ChartData<'doughnut'>;
}
答案#2
事实证明,可以通过使用 any 而不是 ChartOptions 来解决输入错误。
const options: any = {
...
}
正如 LeeLenalee 所指出的,使用这个特定插件与 Chart.js V3 也存在问题,但使用 any 在另一个类似的插件中是可行的。
