/** * 用echarts封装的x轴为时间轴的组件 * echarts中option的具体配置法详见: https://echarts.apache.org/zh/option.html * */ import * as echarts from 'echarts'; import genUUID from '../../utils/gen-uuid'; import { useEffect, useState } from 'react'; import React from 'react'; export interface MultiDataPoint extends DataPoint { name?: string; } export interface DataPoint { time?: number; value?: number; } interface IProps { q_data: MultiDataPoint[], precision: number, width?: number, height?: number, type?: string, //默认值为line,即折线图,可选为直方图bar padding?: {left?:number|string, right?:number|string, top?:number|string, bottom?:number|string} //图表内边距 } export default function MultiEChart(props: IProps){ const uuid = genUUID(); const [showChart, setShowChart] = useState(); useEffect(() => { let tmpChart = echarts.init(document.getElementById(uuid) as any); tmpChart.resize({height:props.height, width:props.width}); tmpChart.setOption(generateOption() as any); setShowChart(tmpChart); }, []) useEffect(() => { if(showChart){ showChart.setOption(generateOption() as any); } }, [props.q_data]) useEffect(() => { if(showChart){ if(props.width){ showChart.resize({height:props.height, width:props.width}); }else{ showChart.resize({height:props.height, width:document.body.clientWidth}); } } }, [props.height, props.width]) useEffect(() => { }, [showChart]) const generateOption = () => { let dimensions_set = new Set(); let source_dict = {}; let label_count = 0; props.q_data.forEach(datePoint => { if(source_dict.hasOwnProperty(datePoint.time)){ source_dict[datePoint.time][datePoint.name] = datePoint.value.toFixed(props.precision); }else{ label_count ++; source_dict[datePoint.time] = {time: datePoint.time}; source_dict[datePoint.time][datePoint.name] = datePoint.value.toFixed(props.precision); } if(!dimensions_set.has(datePoint.name)){ dimensions_set.add(datePoint.name); } }) let series = [] dimensions_set.forEach(name => { if(props.type === 'line'){ series.push({name: name, connectNulls: true, type: props.type, encode:{x:"time", y:name}}); }else{ series.push({name: name, barGap: "0%", type: props.type, encode:{x:"time", y:name}}); } }) return { legend: {top: "2.5%", right:"2%", orient:"horizontal", itemGap:25}, grid: props.padding, dataset: { source: Object.values(source_dict), }, xAxis: { type: 'time', minInterval: 3600 * 24 * 1000, // splitLine: { // show: false, // }, // boundaryGap:true, boundaryGap: ['10%', '40%'], axisTick: { alignWithLabel: true }, splitNumber: label_count }, yAxis: { type: 'value', }, tooltip: { trigger: 'axis', axisPointer: { type: "shadow" }}, // axis item none三个值 series: series } } return
} MultiEChart.defaultProps = { q_data: [], precision: 0, height: 250, type: "line", padding: { } }