好,我给你做一个 React 19 通用 ECharts 组件 ,
支持饼图 / 折线图 / 柱状图,colors
可选,不传也能显示,防止重复渲染。
1. src/services/echarts.ts
注册所有需要的图表类型和组件(不用再分开写折线/饼图/柱状图)
// src/services/echarts.ts
import * as echarts from 'echarts/core';
import {
TitleComponent,
TooltipComponent,
GridComponent,
LegendComponent,
ToolboxComponent
} from 'echarts/components';
import { LineChart, PieChart, BarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
// 按需注册组件
echarts.use([
TitleComponent,
TooltipComponent,
GridComponent,
LegendComponent,
ToolboxComponent,
LineChart,
PieChart,
BarChart,
CanvasRenderer
]);
export default echarts;
2. src/components/EChartsBase.tsx
一个通用的 React 19 ECharts 组件
// src/components/EChartsBase.tsx
import React, { useRef, useEffect } from 'react';
import echarts from '@/services/echarts';
interface EChartsBaseProps {
option: echarts.EChartsOption;
width?: string;
height?: string;
}
const EChartsBase: React.FC<EChartsBaseProps> = ({
option,
width = '100%',
height = '400px'
}) => {
const chartRef = useRef<HTMLDivElement | null>(null);
const chartInstance = useRef<echarts.EChartsType | null>(null);
useEffect(() => {
if (chartRef.current) {
// 如果已有实例,先销毁,防止 React 19 重复渲染
if (chartInstance.current) {
chartInstance.current.dispose();
}
chartInstance.current = echarts.init(chartRef.current);
chartInstance.current.setOption(option);
}
// 监听窗口大小变化
const handleResize = () => {
chartInstance.current?.resize();
};
window.addEventListener('resize', handleResize);
return () => {
chartInstance.current?.dispose();
window.removeEventListener('resize', handleResize);
};
}, [option]);
return <div ref={chartRef} style={{ width, height }} />;
};
export default EChartsBase;
3. 使用示例(不传 colors
也能显示)
// src/pages/DemoCharts.tsx
import React from 'react';
import EChartsBase from '@/components/EChartsBase';
export default function DemoCharts() {
const pieOption = {
title: { text: '示例饼图', left: 'center' },
tooltip: { trigger: 'item' },
legend: { bottom: 0 },
series: [
{
name: '访问来源',
type: 'pie',
radius: '50%',
data: [
{ value: 1048, name: '搜索引擎' },
{ value: 735, name: '直接访问' },
{ value: 580, name: '邮件营销' }
]
}
]
};
const lineOption = {
title: { text: '示例折线图' },
tooltip: { trigger: 'axis' },
xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] },
yAxis: { type: 'value' },
series: [
{ data: [150, 230, 224, 218, 135, 147, 260], type: 'line', smooth: true }
]
};
const barOption = {
title: { text: '示例柱状图' },
tooltip: {},
xAxis: { type: 'category', data: ['苹果', '香蕉', '橘子', '梨子'] },
yAxis: { type: 'value' },
series: [
{ data: [5, 20, 36, 10], type: 'bar' }
]
};
return (
<div style={{ padding: 20 }}>
<EChartsBase option={pieOption} height="300px" />
<EChartsBase option={lineOption} height="300px" />
<EChartsBase option={barOption} height="300px" />
</div>
);
}
✅ 特点:
-
React 19 兼容
-
饼图 / 折线图 / 柱状图通用
-
colors
可选,不传也正常显示 -
自动销毁实例,避免 React 19 重复渲染导致的图表不显示
-
自动响应窗口大小变化