react如何使用echarts
安装依赖
在React项目中使用ECharts前,需安装ECharts核心库和React封装库。通过npm或yarn安装以下依赖:
npm install echarts echarts-for-react
# 或
yarn add echarts echarts-for-react
基础使用示例
创建一个基础图表组件,引入ReactECharts并配置选项:

import React from 'react';
import ReactECharts from 'echarts-for-react';
const BasicChart = () => {
const option = {
title: { text: '基础折线图' },
tooltip: {},
xAxis: { data: ['周一', '周二', '周三', '周四', '周五'] },
yAxis: {},
series: [{ name: '销量', type: 'line', data: [5, 20, 36, 10, 10] }]
};
return <ReactECharts option={option} style={{ height: '400px' }} />;
};
export default BasicChart;
动态数据更新
通过React状态管理实现图表数据动态更新:
import React, { useState, useEffect } from 'react';
import ReactECharts from 'echarts-for-react';
const DynamicChart = () => {
const [data, setData] = useState([5, 20, 36, 10, 10]);
useEffect(() => {
const interval = setInterval(() => {
setData(prev => prev.map(v => v + Math.floor(Math.random() * 10)));
}, 2000);
return () => clearInterval(interval);
}, []);
const option = {
xAxis: { data: ['A', 'B', 'C', 'D', 'E'] },
yAxis: {},
series: [{ type: 'bar', data }]
};
return <ReactECharts option={option} style={{ height: '400px' }} />;
};
主题与自定义样式
使用ECharts主题或自定义样式:

import React from 'react';
import ReactECharts from 'echarts-for-react';
import 'echarts/theme/dark'; // 引入内置主题
const ThemedChart = () => {
const option = {
backgroundColor: '#2c343c',
series: [{
type: 'pie',
data: [
{ value: 335, name: '直接访问' },
{ value: 310, name: '邮件营销' }
],
label: { color: '#fff' }
}]
};
return (
<ReactECharts
option={option}
theme="dark"
style={{ height: '500px' }}
/>
);
};
事件处理
绑定图表事件实现交互逻辑:
import React from 'react';
import ReactECharts from 'echarts-for-react';
const EventChart = () => {
const onChartClick = (params) => {
console.log('点击事件:', params);
};
const option = {
series: [{ type: 'pie', data: [{ value: 335 }, { value: 310 }] }]
};
return (
<ReactECharts
option={option}
onEvents={{
'click': onChartClick
}}
/>
);
};
按需引入模块
优化打包体积,按需引入ECharts模块:
import React from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { GridComponent } from 'echarts/components';
// 注册必要组件
echarts.use([BarChart, GridComponent]);
const CustomChart = () => {
const option = { /* ... */ };
return <ReactECharts echarts={echarts} option={option} />;
};






