BarChart.js 1.79 KB
Newer Older
崔佳豪's avatar
崔佳豪 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
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 },
    ]),
);

25 26 27
const BarChart = forwardRef((props, ref) => {
  const { category, dataSource } = props;

崔佳豪's avatar
崔佳豪 committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
  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]);

55 56 57
  const restProps = _.omit(props, ['category', 'dataSource']);

  return <ECharts ref={ref} option={option} {...restProps} />;
崔佳豪's avatar
崔佳豪 committed
58 59 60 61 62 63 64 65 66 67 68 69
});

BarChart.PropTypes = {
  category: propTypes.array,
  dataSource: propTypes.objectOf({
    name: propTypes.string,
    data: propTypes.array,
    unit: propTypes.unit,
  }),
};

export default BarChart;