在react项目中需要使用echarts的高阶组件,当使用echarts的时候,只需要使用高阶组件包围即可
高阶组件代码如下:
import React, { memo, useEffect, useRef } from 'react';
import * as echarts from 'echarts';
const HOCEcharts = memo((props) => {
const element = useRef<any>(null);
const chart = useRef<any>(null);
const { options } = props;
const resizeAll = () => {
chart.current.resize()
}
useEffect(() => {
setTimeout(() => {
chart.current = echarts.init(element.current);
window.removeEventListener('resize', resizeAll)
if(chart.current){
window.addEventListener('resize', resizeAll);
chart.current.setOption(options, true)
}
}, 20)
},[])
useEffect(() => {
window.removeEventListener('resize', resizeAll)
if(chart.current){
window.addEventListener('resize', resizeAll);
chart.current.setOption(options, true)
}
}, [options])
return <div ref={element} style={{width: '100%', height: '100%'}}></div>
})
export default HOCEcharts;
组件代码如下:
import React, { memo, useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import _ from 'lodash';
import HOCEcharts from '../../HOCEcharts/EchartsHoc';
function areEqual(prevProps: any, nextProps: any) {
return JSON.stringify(prevProps) === JSON.stringify(nextProps);
}
const Bar: any = memo(({datasource, style, ...props}: any) => {
const { barData, barLenged } = props;
const option: any = {
grid:{
left:'5%',
top: '10%',
right: '5%',
bottom: '10%'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
crossStyle: {
color: '#999'
}
}
},
legend: {
data: barLenged
},
xAxis: [
{
type: 'category',
data: _.map(_.get(barData, 'data'), (item) => (_.get(item, 'days'))),
axisPointer: {
type: 'shadow'
}
}
],
yAxis: [
{
type: 'value',
min: 0,
axisLabel: {
formatter: '{value}'
}
}
],
series: [
{
name: barLenged[0],
type: 'bar',
tooltip: {
valueFormatter: function (value: any) {
return value;
}
},
itemStyle: {
color: '#647bbf'
},
data: _.map(_.get(barData, 'data'), (item) => (_.get(item, 'current')))
},
{
name: barLenged[1],
type: 'bar',
tooltip: {
valueFormatter: function (value: any) {
return value;
}
},
itemStyle: {
color: '#35c9c8'
},
data: _.map(_.get(barData, 'data'), (item) => (_.get(item, 'lastOPay')))
}
]
}
return <HOCEcharts
options={option}
/>;
}, areEqual)
export default Bar;
这是对柱状图的实现,可以自行实现查看效果图。