react如何引用echarts饼状图
安装依赖
在项目中安装 ECharts 和 React 的 ECharts 封装库:
npm install echarts echarts-for-react
引入组件和 ECharts
在需要使用的组件中引入必要的模块:

import React from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
准备图表配置
创建饼状图的配置对象:
const getOption = () => ({
title: {
text: '示例饼图',
subtext: '虚拟数据',
left: 'center'
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 'left',
data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
},
series: [
{
name: '访问来源',
type: 'pie',
radius: '50%',
data: [
{ value: 335, name: '直接访问' },
{ value: 310, name: '邮件营销' },
{ value: 234, name: '联盟广告' },
{ value: 135, name: '视频广告' },
{ value: 1548, name: '搜索引擎' }
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
});
渲染图表组件
在组件中渲染 ECharts 实例:

function PieChart() {
return (
<ReactECharts
option={getOption()}
style={{ height: '400px', width: '100%' }}
className="echarts-for-react"
/>
);
}
export default PieChart;
自定义主题(可选)
如需使用自定义主题,可注册主题后应用:
// 引入主题文件
import { registerTheme } from 'echarts';
registerTheme('myTheme', {
backgroundColor: '#f4cccc',
color: ['#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53']
});
// 在组件中使用主题
<ReactECharts
option={getOption()}
theme="myTheme"
/>
响应式处理
添加窗口大小变化时的自适应逻辑:
function PieChart() {
const chartRef = React.useRef(null);
React.useEffect(() => {
const handleResize = () => {
if (chartRef.current) {
chartRef.current.getEchartsInstance().resize();
}
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return (
<ReactECharts
ref={chartRef}
option={getOption()}
style={{ height: '400px', width: '100%' }}
/>
);
}
注意事项
- 确保在服务器端渲染(SSR)环境中正确导入 ECharts,可能需要动态导入
- 大数据量时考虑使用懒加载或虚拟滚动优化性能
- TypeScript 项目需要安装对应的类型声明文件:
npm install --save-dev @types/echarts






