下载
npx create-react-app my-echarts
创建公共组件
import React, { useState, useEffect,useMemo } from 'react';
import * as echarts from "echarts";
const EChartsComponent = ({ option }) => {
const [echartsInstance, setEchartsInstance] = useState(null);
useEffect(() => {
if (!echartsInstance) {
// 基于准备好的dom,初始化echarts实例
const echartsDom = document.getElementById('myChart');
const instance = echarts.init(echartsDom);
setEchartsInstance(instance);
}
// 监听窗口大小变化
window.onresize = () => {
if (echartsInstance) {
echartsInstance.resize();
}
};
// 清理函数
return () => {
window.onresize = null;
if (echartsInstance) {
echartsInstance.dispose();
}
};
}, [echartsInstance]);
let Each=useMemo(() => {
if (echartsInstance) {
echartsInstance.setOption(option);
}
}, [echartsInstance]);
return <div id="myChart" style={{ width: '600px', height: '400px' }} />;
};
export default EChartsComponent;
父组件调用
import React from 'react';
import Eachex from './components/Eachex'
const App = () => {
const option = {
title: {
text: '折线图'
},
tooltip: {
trigger: 'none'
},
legend: {
data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine'],
icon:'circle',
itemwidth:10,//legend图标宽度
itemHeight:10 // legend图标高度
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
name: 'Email',
type: 'line',
stack: 'Total',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: 'Union Ads',
type: 'line',
stack: 'Total',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: 'Video Ads',
type: 'line',
stack: 'Total',
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: 'Direct',
type: 'line',
stack: 'Total',
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: 'Search Engine',
type: 'line',
stack: 'Total',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
};
return (
<div>
<h1>React 函数组件 + ECharts 示例</h1>
<Eachex option={option} />
</div>
);
};
export default App;
title
标题组件,包含主标题和副标题。
legend
图例组件。
图例组件展现了不同系列的标记(symbol),颜色和名字。可以通过点击图例控制哪些系列不显示。
grid
直角坐标系内绘图网格,单个 grid 内最多可以放置上下两个 X 轴,左右两个 Y 轴。可以在网格上绘制折线图,柱状图,散点图(气泡图)。