react中如何使用echarts
安装 ECharts 依赖
在 React 项目中安装 ECharts 核心库和 React 适配器:
npm install echarts echarts-for-react
基础使用示例
创建一个简单的柱状图组件:
import React from 'react';
import ReactECharts from 'echarts-for-react';
function BarChart() {
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar'
}]
};
return <ReactECharts option={option} />;
}
export default BarChart;
异步数据加载
处理动态数据更新:
import React, { useEffect, useState } from 'react';
import ReactECharts from 'echarts-for-react';
function DynamicChart() {
const [option, setOption] = useState({});
useEffect(() => {
// 模拟异步数据获取
fetchData().then(data => {
setOption({
series: [{
type: 'pie',
data: data
}]
});
});
}, []);
return <ReactECharts option={option} />;
}
主题定制
使用 ECharts 内置主题或自定义主题:
import React from 'react';
import ReactECharts from 'echarts-for-react';
import 'echarts/theme/dark';
function ThemedChart() {
const option = {
/* 图表配置 */
};
return <ReactECharts option={option} theme="dark" />;
}
事件处理
添加图表交互事件:
function ChartWithEvents() {
const onChartClick = (params) => {
console.log('Chart clicked:', params);
};
const onEvents = {
click: onChartClick
};
return (
<ReactECharts
option={/* 图表配置 */}
onEvents={onEvents}
/>
);
}
响应式设计
实现图表自适应容器大小:
function ResponsiveChart() {
const option = {
/* 图表配置 */
};
return (
<ReactECharts
option={option}
style={{ height: '100%', width: '100%' }}
opts={{ renderer: 'svg' }}
/>
);
}
性能优化
对于大数据量图表使用按需加载:
import React from 'react';
import ReactECharts from 'echarts-for-react';
import 'echarts/lib/chart/line';
import 'echarts/lib/component/tooltip';
function OptimizedChart() {
const option = {
/* 精简配置 */
};
return <ReactECharts option={option} />;
}
服务端渲染支持
在 Next.js 等框架中使用:

import React from 'react';
import ReactECharts from 'echarts-for-react';
import dynamic from 'next/dynamic';
const DynamicChart = dynamic(
() => import('echarts-for-react'),
{ ssr: false }
);
function SSRChart() {
return <DynamicChart option={/* 配置 */} />;
}






