ECharts.js 1.64 KB
Newer Older
1 2 3 4 5
/*
 * @Title:
 * @Author: hongmye
 * @Date: 2023-09-27 11:51:16
 */
崔佳豪's avatar
崔佳豪 committed
6 7 8 9
import { ConfigProvider } from 'antd';
import classNames from 'classnames';
import ReactEcharts from 'echarts-for-react';
import { omit } from 'lodash';
10 11
import ResizeObserver from 'rc-resize-observer';
import React, { memo, useMemo, useState } from 'react';
崔佳豪's avatar
崔佳豪 committed
12 13
import buildOption from './utils';

14 15 16 17
const ECharts = memo(
  React.forwardRef((props, ref) => {
    const { getPrefixCls } = React.useContext(ConfigProvider.ConfigContext);
    const prefixCls = getPrefixCls('basic-chart');
18
    const [isShow, setIsShow] = useState('hidden');
19
    const chartProps = omit(props, ['className', 'option']);
20

21 22 23
    const option = useMemo(() => {
      return buildOption(props.option);
    }, [props.option]);
杨思琦's avatar
杨思琦 committed
24
    if (ref && ref.current && ref.current.getEchartsInstance) {
杨思琦's avatar
杨思琦 committed
25 26 27 28
      ref.current.getEchartsInstance().clear();
      ref.current.getEchartsInstance().setOption(option);
      ref.current.getEchartsInstance().resize();
    }
29 30 31 32 33 34 35 36 37

    const onResize = ({ width, height }) => {
      if (width && height) {
        setIsShow('visible');
        ref?.current?.getEchartsInstance && ref.current.getEchartsInstance().resize();
      } else {
        setIsShow('hidden');
      }
    };
38
    return (
39 40 41 42 43 44 45 46 47 48 49
      <ResizeObserver onResize={onResize}>
        <div style={{ width: '100%', height: '100%', visibility: isShow }}>
          <ReactEcharts
            ref={ref}
            className={classNames(prefixCls, props.className)}
            style={{ width: '100%', height: '100%' }}
            option={option}
            {...chartProps}
          />
        </div>
      </ResizeObserver>
50 51 52
    );
  }),
);
崔佳豪's avatar
崔佳豪 committed
53 54

export default ECharts;