/** * 用antv/g2封装的折线图组件 * 具体写法可参考http://antv-2018.alipay.com/zh-cn/g2/3.x/demo/line/curved.html * */ import { useEffect, useState } from 'react' import { Chart } from '@antv/g2'; 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 } export default function MultiLineChart(props: IProps) { const [lineChart, setLineChart] = useState(); useEffect(() => { const chart = new Chart({ container: 'tn-query-multi-container', autoFit: true, height: props.height || 300, padding: [30, 80, 30, 40], // width: props.width || null, }); chart.data(props.q_data); chart.tooltip({ showCrosshairs: true, shared: true, crosshairs: { type: 'xy', }, }) chart.scale({ time: { type: 'timeCat', range: [0, 0.95], tickCount: 5, alias: '时间', mask: 'YYYY-MM-DD ' }, value: { nice: true, formatter: (val: number) => `${val.toFixed(props.precision)}`, alias: '数值', tickCount: 6, } }); chart .line() .position('time*value') .color('name') ; chart .point() .position('time*value') .color('name') .shape('circle') .style({ fillOpacity: 1 }) ; chart.legend({ position: 'right' }) chart.axis('value', { grid: { line: { style: { lineDash: [10, 5], lineWidth: 1, stroke: '#ccc' } } }, line: { style: { lineWidth: 1, stroke: '#666' } } }) chart.axis('time', { line: { style: { lineWidth: 1, stroke: '#666' } } }) // this.lineChart = chart; setLineChart(chart); chart.render(); return (() => { chart.clear(); chart.destroy(); }) }, []) useEffect(() => { if (!lineChart) return; lineChart.changeData(props.q_data); }, [lineChart, props.q_data]) useEffect(() => { if (!lineChart) return; // lineChart.height = props.height; let ele = document.getElementById('tn-query-multi-container'); lineChart.changeSize(ele?.clientWidth, props.height); // lineChart.changeData(props.q_data); }, [props.height]) return (
) }