React中使用Echarts封装

2,196 阅读1分钟

         前段时间,项目中用到echarts图表,针对项目中可能后期还会有人使用,单独抽离出来作为一个components供大家使用,废话不多说,直接上代码

import React, {
  ReactElement,
  useLayoutEffect,
  useImperativeHandle,
  useRef,
  forwardRef,
} from 'react';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/dataZoom';
import 'echarts/lib/component/legend';
import { throttle } from 'lodash';
import useDidMount from '@/hooks/useDidMount';

interface Props {
  id: string;
  option: echarts.EChartOption;
  style: React.CSSProperties;
}
export interface RefInstance {
  setOption: (option: echarts.EChartOption) => void;
}

function Echarts(props: Props, ref: React.Ref<RefInstance>): ReactElement {
  const { id, option, style } = props;
  const instance = useRef<echarts.ECharts>();

  useImperativeHandle(ref, () => {
    return {
      setOption(opt: echarts.EChartOption) {
        if (instance.current) {
          instance.current.setOption(opt);
        }
      },
    };
  });
  useLayoutEffect(() => {
    const el = document.getElementById(id);

    if (el) {
      instance.current = echarts.init(document.getElementById(id) as HTMLDivElement, undefined, {
        renderer: 'svg',
      });
      instance.current.setOption(option);
    }
  }, [id, option]);

  useDidMount(() => {
    const func = throttle(() => {
      if (instance.current) {
        instance.current.resize();
      }
    }, 300);

    window.addEventListener('resize', func);

    return () => {
      window.removeEventListener('resize', func);
    };
  });

  return <div id={id} style={style} />;
}

export default forwardRef(Echarts)    

   封装完成直接再页面中使用

import React, { useRef } from 'react';
import Echarts, { RefInstance } from '@/components/Echarts'; // 引入Echarts

function Index(){
     const echarts = useRef<RefInstance>();
       <Echarts
          id="SHENGAO"
          ref={echarts as React.Ref<RefInstance>}
          style={{
             width:100%',
             height: '400px',
          }}
          option={options(lineRecord, standardData, birthday, currentKey) as echarts.EChartOption}
         />
}