react如何使用echarts
安装 ECharts 依赖
在 React 项目中安装 ECharts 核心库和 React 适配器:
npm install echarts echarts-for-react
引入 ECharts 组件
在 React 组件中导入 ECharts 和 React 适配器:
import React from 'react';
import ReactECharts from 'echarts-for-react';
配置图表选项
定义图表的配置项(option),例如一个简单的柱状图:
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'
}]
};
渲染图表组件
在组件中渲染 ReactECharts 并传入配置项:
function App() {
return (
<div>
<ReactECharts option={option} />
</div>
);
}
动态更新图表
通过 React 的状态管理动态更新图表数据:
const [data, setData] = useState([120, 200, 150, 80, 70, 110, 130]);
const updateChart = () => {
setData(data.map(value => value + Math.random() * 50));
};
return (
<div>
<ReactECharts option={{ ...option, series: [{ data }] }} />
<button onClick={updateChart}>Update Data</button>
</div>
);
主题定制
使用 ECharts 的主题或自定义样式:
import 'echarts/theme/dark';
<ReactECharts option={option} theme="dark" />
事件绑定
通过 onEvents 属性绑定图表事件:
const onChartClick = (params) => {
console.log('Chart clicked:', params);
};
<ReactECharts option={option} onEvents={{ click: onChartClick }} />
按需引入模块
优化打包体积,按需引入 ECharts 模块:

import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([BarChart, GridComponent, CanvasRenderer]);






