/** * 用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 CateGoryData { axisName: string; legendName?: string; value: number; } interface IProps { q_data: CateGoryData[], precision: number, width?: number, height?: number, type?: string, //默认值为line,即折线图,可选为直方图bar color?: string //该颜色只对二维数据有效 padding?: {left?:number|string, right?:number|string, top?:number|string, bottom?:number|string} //图表内边距 } export default function CategoryEChart(props: IProps){ const uuid = genUUID(); const [showChart, setShowChart] = useState(); useEffect(() => { if(!showChart){ 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 series = []; if(props.q_data.length === 0){ //没有数据。返回空表 }else{ if(props.q_data[0].legendName){ //如果legendName存在,为三维数据 let data_dict = {}; props.q_data.forEach(datePoint => { if(data_dict.hasOwnProperty(datePoint.legendName)){ data_dict[datePoint.legendName].push([datePoint.axisName, datePoint.value.toFixed(props.precision)]); }else{ data_dict[datePoint.legendName] = []; data_dict[datePoint.legendName].push([datePoint.axisName, datePoint.value.toFixed(props.precision)]); } }) Object.keys(data_dict).forEach(legendName => { series.push({name:legendName, data:data_dict[legendName], type:props.type}) }); }else{ //legendName不存在,为二维数据 let data = []; props.q_data.forEach(datePoint => { data.push([datePoint.axisName, datePoint.value.toFixed(props.precision)]); }) series = [ {data:data, type:props.type, color:props.color, barWidth: '35%'} ] } } return { legend: {top: "2.5%", right:"2%", orient:"horizontal", itemGap:25}, grid: props.padding, xAxis: { type: 'category', splitLine: { show: false, }, boundaryGap:true, axisTick: { alignWithLabel: true }, }, yAxis: { type: 'value', min: function (value) { return Math.max(value.min - 20, 0); } }, tooltip: { trigger: 'axis', axisPointer: { type: "shadow" }}, // axis item none三个值 series: series } } return
} CategoryEChart.defaultProps = { q_data: [], precision: 0, height: 250, type: "line", color: "#eaeaea", padding:{ } }