react项目如何使用echarts
安装 ECharts 依赖
在 React 项目中安装 ECharts 核心库和 React 适配器:
npm install echarts echarts-for-react
# 或使用 yarn
yarn add echarts echarts-for-react
基础使用示例
创建一个简单的折线图组件:
import React from 'react';
import ReactECharts from 'echarts-for-react';
const LineChart = () => {
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line'
}]
};
return <ReactECharts option={option} />;
};
export default LineChart;
按需引入模块
ECharts 支持按需引入以减小打包体积:
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
// 注册必要组件
echarts.use([LineChart, GridComponent, CanvasRenderer]);
// 后续使用方式与基础示例相同
动态更新图表数据
通过 React 状态管理实现数据动态更新:
import React, { useState, useEffect } from 'react';
import ReactECharts from 'echarts-for-react';
const DynamicChart = () => {
const [data, setData] = useState([120, 200, 150, 80, 70, 110, 130]);
useEffect(() => {
const interval = setInterval(() => {
setData(prevData => prevData.map(value => value + Math.random() * 10 - 5));
}, 1000);
return () => clearInterval(interval);
}, []);
const option = {
xAxis: { type: 'category', data: ['A', 'B', 'C', 'D', 'E', 'F', 'G'] },
yAxis: { type: 'value' },
series: [{ data, type: 'bar' }]
};
return <ReactECharts option={option} style={{ height: 400 }} />;
};
主题定制
使用 ECharts 内置主题或自定义主题:
- 注册主题:
import * as echarts from 'echarts'; import { theme } from './customTheme.json'; // 自定义主题文件
echarts.registerTheme('myTheme', theme);
2. 应用主题:
```jsx
<ReactECharts
option={option}
theme="myTheme"
style={{ height: '500px' }}
/>
事件处理
绑定图表交互事件:
const onChartClick = (params) => {
console.log('点击事件参数:', params);
};
<ReactECharts
option={option}
onEvents={{
click: onChartClick,
legendselectchanged: (params) => console.log('图例切换:', params)
}}
/>
响应式设计
通过监听窗口变化实现自适应:
import { useResizeDetector } from 'react-resize-detector';
const ResponsiveChart = () => {
const { width, ref } = useResizeDetector();
return (
<div ref={ref}>
<ReactECharts
option={option}
style={{ height: width ? width * 0.6 : '100%' }}
/>
</div>
);
};






