react如何引入echarts
安装依赖
在项目中安装 echarts 和 echarts-for-react 库。echarts-for-react 是一个封装好的 React 组件,方便在 React 中使用 ECharts。
npm install echarts echarts-for-react
引入基本图表
创建一个 React 组件并引入 ECharts 图表。以下是一个简单的折线图示例:
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 React from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
GridComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
// 注册必要的组件
echarts.use([
LineChart,
TitleComponent,
TooltipComponent,
GridComponent,
CanvasRenderer
]);
const CustomChart = () => {
const option = {
title: {
text: '按需引入示例'
},
tooltip: {},
xAxis: {
data: ['A', 'B', 'C', 'D', 'E']
},
yAxis: {},
series: [
{
name: '数据',
type: 'line',
data: [5, 20, 36, 10, 10]
}
]
};
return <ReactECharts echarts={echarts} option={option} />;
};
export default CustomChart;
动态更新数据
通过 React 的状态管理动态更新图表数据:
import React, { useState, useEffect } from 'react';
import ReactECharts from 'echarts-for-react';
const DynamicChart = () => {
const [data, setData] = useState([10, 20, 30, 40, 50]);
useEffect(() => {
const interval = setInterval(() => {
setData(prevData =>
prevData.map(value => value + Math.floor(Math.random() * 10) - 5)
);
}, 1000);
return () => clearInterval(interval);
}, []);
const option = {
xAxis: {
type: 'category',
data: ['A', 'B', 'C', 'D', 'E']
},
yAxis: {
type: 'value'
},
series: [
{
data,
type: 'bar'
}
]
};
return <ReactECharts option={option} />;
};
export default DynamicChart;
主题配置
可以使用 ECharts 的主题功能自定义图表样式:
import React from 'react';
import ReactECharts from 'echarts-for-react';
import { dark } from 'echarts/themes';
const ThemedChart = () => {
const option = {
title: {
text: '深色主题示例'
},
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} theme={dark} />;
};
export default ThemedChart;
事件处理
为图表添加事件处理函数:

import React from 'react';
import ReactECharts from 'echarts-for-react';
const EventChart = () => {
const onChartClick = params => {
console.log('图表点击事件', params);
};
const onEvents = {
click: onChartClick
};
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} onEvents={onEvents} />;
};
export default EventChart;






