echarts官网教程
https://echarts.apache.org/zh/tutorial.html
基于echarts最新版本,在react中对echarts的封装,使用时传入对应图表的options
option可根据echarts官方文档配置
1、echarts渲染封装
import React, { useCallback, useEffect, useRef } from 'react';
// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core';
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';
// 设备分辨率
const dpr = window.devicePixelRatio;
const Chart = ({ renderType = 'canvas', options, style, components = [] }) => {
const chartRef = useRef();
const chartInstance = useRef(null);
//初始化图表,设置配置项
const renderChart = useCallback(() => {
const render = echarts?.getInstanceByDom(chartRef.current);
if (render) {
chartInstance.current = render;
} else {
chartInstance.current = echarts?.init(chartRef.current, null, {
renderer: renderType,
});
}
chartInstance.current?.setOption(options);
}, [chartRef, options, renderType]);
useEffect(() => {
// 注册必须的组件
echarts?.use([CanvasRenderer, ...components]);
}, []);
//监听屏幕变化,重绘图表
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
});
useEffect(() => {
renderChart();
return () => {
const { current } = chartInstance ?? {};
if (current) {
current.dispose();
}
};
}, [chartInstance, renderChart]);
const handleResize = () => {
const chart = chartInstance?.current;
if (chart) {
chart.resize();
}
};
return (
<div
ref={chartRef}
style={{
height: `${260 * dpr}px`,
width: `calc(100vw - .32rem)`,
...style,
}}
/>
);
};
export default Chart;
2、使用(下边是仪表盘图表配置)
import React from 'react';
// 引入柱状图图表,图表后缀都为 Chart
import { GaugeChart } from 'echarts/charts';
// 引入封装好的组件
import Chart from '../Chart';
import styles from './index.less';
const getOption = (progress) => {
return {
series: {
type: 'gauge',
radius: '160%',
center: ['50%', '100%'],
startAngle: 180,
endAngle: 0,
min: 0,
max: 100,
splitNumber: 12,
itemStyle: {
color: {
type: 'linear',
x: 1,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{
offset: 0,
color: '#A6746B',
},
{
offset: 1,
color: '#DAABA2',
},
],
},
},
progress: {
show: true,
width: 30,
},
pointer: {
show: false,
},
axisLine: {
lineStyle: {
width: 30,
color: [[1, '#ddd']],
},
},
axisTick: {
show: false,
},
splitLine: {
show: false,
},
axisLabel: {
show: false,
},
anchor: {
show: false,
},
title: {
show: false,
},
detail: {
valueAnimation: true,
width: '60%',
lineHeight: 40,
height: '15%',
borderRadius: 8,
offsetCenter: [0, '-15%'],
fontSize: 72,
fontWeight: 'bolder',
formatter: '{value}%',
color: '#373737',
},
data: [
{
value: progress,
},
],
},
};
};
export default ({ progress }) => {
return (
<Chart
style={{ height: '40vw' }}
options={getOption(progress)}
components={[GaugeChart]}
/>
);
};
3、效果图