我在我的项目中使用类型记录,我试图改变图表的类型,例如按一下按钮。react chartjs-2的正式文档将类型声明为const,所以类型记录不编译它。我该怎么做,如果真的不可能的话?
我的代码:
const Stats = () => {
const [type, setType] = useState('bar');
const data = {
labels,
datasets: [
{
// in offical docs
// type: 'bar' as const,
type: type,
label: 'Dataset 1',
borderColor: 'rgb(255, 99, 132)',
borderWidth: 2,
fill: false,
data: randomArray(),
},
{
type: type,
label: 'Dataset 2',
backgroundColor: 'rgb(75, 192, 192)',
data: randomArray(),
borderColor: 'white',
borderWidth: 2,
},
{
type: type,
label: 'Dataset 3',
backgroundColor: 'rgb(53, 162, 235)',
data: randomArray(),
},
],
};
return (
<div>
<Chart type='bar' data={data} />
<Button onClick={ () => setType('line')}>Change type</Button>
</div>
);
};发布于 2022-01-16 13:18:59
您可以这样做,从ChartType中导入chart.js,如
import {ChartType} from 'chart.js'然后将useState代码更改为
const [type, setType] = useState<ChartType>('bar');现在它应该起作用了
发布于 2022-03-08 08:35:06
您可以使用开关箱。
const [chartType, setChartType] = useState("Line");
...
...
return(
...
{(() => {
switch (chartType) {
case "Line":
return <Line data={gdata} options={goptions} />;
case "Bar":
return <Bar data={gdata} options={goptions} />;
case "Pie":
return <Pie data={gdata} options={goptions} />;
case "Radar":
return <Radar data={gdata} options={goptions} />;
case "Scatter":
return <Scatter data={gdata} options={goptions} />;
default:
return <Line data={gdata} options={goptions} />;
}
})()}
)https://stackoverflow.com/questions/70729326
复制相似问题