import React, { useMemo, forwardRef } from 'react'; import ECharts from './ECharts'; import * as echarts from 'echarts/core'; import propTypes from 'prop-types'; import _ from 'lodash'; // 基础柱状图 const isCategory = (category) => category !== undefined; const isStack = (stack) => stack === undefined || stack === null; const gradientColors = [ ['#1685ff', '#74bcff'], ['#00b809', '#66d46b'], ['#ffa200', '#ffc766'], ['#00c4bd', '#66dccd'], ['#ff6b37', '#ff9773'], ['#986aff', '#c1a6ff'], ].map( ([from, to]) => new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: from }, { offset: 1, color: to }, ]), ); const BarChart = forwardRef((props, ref) => { const { category, dataSource } = props; const option = useMemo(() => { const xAxis = isCategory(category) ? { type: 'category', data: category, } : { type: 'time', }; const hasUnitItem = dataSource.find((item) => item.unit); const yAxis = !!hasUnitItem ? { name: `(${hasUnitItem.unit})` } : {}; const series = dataSource.map((item, index) => { const config = _.omit(item, ['type']); const itemStyle = isStack(config.stack) ? { color: gradientColors[index % gradientColors.length], } : {}; return { type: 'bar', ...itemStyle, ...config, }; }); return { xAxis, yAxis, series }; }, [category, dataSource]); const restProps = _.omit(props, ['category', 'dataSource']); return <ECharts ref={ref} option={option} {...restProps} />; }); BarChart.PropTypes = { category: propTypes.array, dataSource: propTypes.objectOf({ name: propTypes.string, data: propTypes.array, unit: propTypes.unit, }), }; export default BarChart;