复制粘贴即可使用! react封装echart图表基础组件

用法:

getOption(chart1)对应的option只要复制echart你需要的示例option即可

      <Chart
         style={{ width: "100%", height: "460px" }}
         option={getOption(chart1)}
        />

实现(声明一个Chart组件)

import React, { useRef, useEffect } from "react";
import * as echarts from "echarts";

interface ChartProps {
  option: Record<string, unknown> | null;
  style: {
    width: string;
    height: string;
  };
  className?: string;

  onRender?: (instance: any) => void;
}

const Index = (props: ChartProps) => {
  const chartDom = useRef<any>();
  const instance = useRef<any>();

  function showLoading(_instance: {
    showLoading: (
      arg0: string,
      arg1: {
        text: string;
        color: string;
        textColor: string;
        maskColor: string;
        zlevel: number;
      }
    ) => void;
  }): void {
    _instance.showLoading("default", {
      text: "",
      color: "#c23531",
      textColor: "#000000",
      maskColor: "rgba(255, 255, 255, 0.8)",
      zlevel: 0,
    });
  }
  // 生命钩子函数
  type Callback = () => void;

  useEffect((): Callback => {
    // 获取实例对象
    instance.current =
      echarts.getInstanceByDom(chartDom.current) ||
      echarts.init(chartDom.current, "");

    // 大小自适应
    const resize = (): void => instance.current.resize();
    window.removeEventListener("resize", resize);
    window.addEventListener("resize", resize);

    // 默认加载状态
    showLoading(instance.current);

    // 销毁并清除状态
    return (): void => {
      echarts.dispose(instance.current);
      window.removeEventListener("resize", resize);
    };
  }, [chartDom]);

  useEffect(() => {
    // 默认加载状态
    showLoading(instance.current);

    // 渲染图表
    if (props.option) {
      if (instance.current) {
        instance.current.hideLoading();
        instance.current.setOption(props.option);
      }
    }

    // 回调函数返回实例
    if (props.onRender) props.onRender(instance.current);
  }, [props]);

  // 返回组件
  return <div ref={chartDom} style={props.style} className={props.className} />;
};

export default Index;

你可能感兴趣的:(前端,react.js,echarts,前端)