基于echarts 灵活封装react饼图组件

基于echarts 灵活封装react饼图组件

这段时间比较忙,没什么时间封装组件库,同事都不怎么会使用echarts,今天随手封装了一个echart的饼图, 百十来行的代码同事用了都说好!
废话不多说封装组件之前,首先要考虑我们的组件,都要包含哪些功能;

  1. 窗口随动,echart的窗口resize,是需要我们自己写的,这个肯定封装(注意要做防抖处理);
  2. 每次设置画布的元素的时候都需要传入宽高,这也需要,省事嘛;
  3. 鬼知道会不会有事件,所以事件也是肯定要的;
  4. 没有数据的时候画布不能空着,加一个暂无数据的展示;
  5. 我在代码中添加一个名为options的对象这里可以补充我没有封装的功能,比如需要图例可以自己定义,传进去也是一样的;
  6. 有增加自然就有删除,删除的属性为deleteOption, 和5一样都需要判断是否属性是否存在,存在则执行,不存在则忽略;

先看看完整体,有兴趣您就继续,没兴趣那就再见来不及握手:
《基于echarts 灵活封装react饼图组件》《基于echarts 灵活封装react饼图组件》

看着还是可以的吧!别问我为什么没有图例,公司多数都是缩略图,图例基本用不上,为了一个不用的多封装一个功能没什么意思!
再看下声明的propTypes和 defaultProp 尽可能少的使用isRequired (个人意见,免得后续使用者,漏传就会报错)
《基于echarts 灵活封装react饼图组件》
是不是有点多? 还好吧,毕竟这么灵活!

作用看下注释就ok了!别说你看不懂啊!s,记住这两个 一定有,因为你不知道后面的使用者或不会传错,注释最好也留下,免得被挖坟!

再往下看,在componentDidMount周期中接受props的属性,组装自己的option:

《基于echarts 灵活封装react饼图组件》

注意:init的时候记住一定要接受key,保证页面的id唯一的,如果两个画板的id重复了,会导致其他处理第一个画板以后其他的画板都是白色的,echarts不会覆盖,所以加入你的画板没有东西,那就看下是不是画板元素存在子元素,或者已经画了图形,其次在init之后我们要clear清理画板 并且取消所有绑定函数(.off),不然下次刷新图形的时候,事件会在挂载
最后在挂一下代码吧,毕竟自己刚开始写博客,技术属实是不怎么样,虽然看的不多,万一要是有人看呢哈哈!!

import React, {PureComponent} from 'react';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/pie';
import 'echarts/lib/component/title';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/toolbox';
import 'echarts/lib/component/graphic';
import PropTypes from 'prop-types';

/*
* 饼图组件可支持环形切换,
* 包含无数据展示,onresize重绘事件
* 可以自定义option, 支持多种鼠标事件
* 暂时未封装图例,图例等其他功能可通过 options自己定义添加
*
* */
const _eventType = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseup', 'mouseover', 'mouseout', 'globalout', 'contextmenu'];

class PieChart extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {}
  }

  static propTypes = {
    chartsData: PropTypes.array.isRequired, // 图形数据
    keys: PropTypes.string.isRequired || PropTypes.number.isRequired, // 唯一标识区分多个饼图,
    getCharts: PropTypes.func, // 把echarts 对象传出去
    onResize: PropTypes.func, // 全局onResize事件,
    eChartsEvent: PropTypes.func, // 图形点击事件, 返回这各图形的数据以及对应的param,echarts 对象

    title: PropTypes.string, // 标题栏,名字
    bgColor: PropTypes.string, // 背景色
    chartColor: PropTypes.array, // 扇形区域颜色
    radius: PropTypes.array, // 半径内圈半径不可以调小不然暂无数据的时候字放不下
    center: PropTypes.array, // 位置调节
    label: PropTypes.bool, // 是否展示label
    maxShow: PropTypes.number, // 需 >= 0 最多展示几个扇形,不传或者值为0 则默认不处理,建议不要大于5
    options: PropTypes.object, // 修改 更新的想要的配置,直接那eCharts的就可以
    deleteOption: PropTypes.oneOf(['title', 'toolbox', 'tooltip', 'graphic']), // 删除不需要的配置
    eventType: PropTypes.oneOf([
      'click', 'dblclick', 'mousedown', 'mousemove',
      'mouseup', 'mouseover', 'mouseout', 'globalout', 'contextmenu'
    ]), // 事件类型
  };

  static defaultProps = {
    title: '',
    bgColor: "#fff",
    chartColor: ['#1890ff', '#13c2c2', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#eb2f96', '#faad14'],
    radius: ['0', '65%'],
    center: ['50%', '55%'],
    label: false,
    eventType: 'click'
  };

  componentDidMount() {
    const {
      chartsData, keys, getCharts, onResize, title, bgColor,
      chartColor, radius, center, label, maxShow, deleteOption, options,
      eChartsEvent, eventType
    } = this.props;

    let newChartsData = [];
    if (maxShow && maxShow >= 0 && chartsData.length > maxShow) {
      chartsData.sort((a, b) => {
        return b.value - a.value;
      });

      newChartsData = chartsData.slice(0, maxShow);
      let total = 0;
      chartsData.map((item, index) => {
        if (index > 4) {
          total += item.value
        }
      });
      newChartsData = [...newChartsData, {value: total, name: '其他'}];
    }
    else {
      newChartsData = [...chartsData]
    }

    let myCharts = echarts.init(document.getElementById(`${keys}_drawingBoard`));

    if (getCharts && typeof func === 'function') {
      getCharts(myCharts);
    }
    myCharts.clear();

    _eventType.map(item => {
      myCharts.off(item);
    });

    //  todo:还差一个点击事件
    let option = {
      color: newChartsData.length ? chartColor : '#bfbfbf',
      title: {
        text: title,
        top: 20,
        x: 'center'
      },
      toolbox: {
        feature: {
          saveAsImage: {
            type: 'png',
            title: '点击下载',
          }
        },
        top: 13,
        right: 13
      },
      tooltip: {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      series: [
        {
          name: title,
          type: 'pie',
          radius,
          center,
          avoidLabelOverlap: false,
          label: {
            show: label,
          },
          labelLine: {
            normal: {
              show: label
            }
          },
          itemStyle: {
            borderWidth: 2, //设置border的宽度有多大
            borderColor: bgColor,
          },
          hoverAnimation: false,
          hoverOffset: 0,
          data: newChartsData.length ? newChartsData : [{value: 0, name: '暂无数据'}],
        },
      ],
      graphic: newChartsData.length
        ? null
        : [{
          type: 'text',
          left: 'center',
          top: radius[0] === '0' ? 'auto' : center[1],
          bottom: 10,
          cursor: 'auto',
          style: {
            text: '暂无数据',
            textAlign: 'center',
            fill: '#bfbfbf',
            fontSize: 16,
            stroke: '#bfbfbf',
            lineWidth: 0
          }
        }]
    };

    if (deleteOption) {
      delete option[deleteOption]
    } // 删除函数

    if (options) {
      option = {...option, ...options}
    } // 补充的options

    myCharts.setOption(option);

    if (eChartsEvent && typeof eChartsEvent === 'function') {
      myCharts.on(eventType, 'series', params => {
        eChartsEvent(params, chartsData, myCharts);
      });
    }

    window.onresize = () => {
      let target = this;
      if (target.resizeFlag) {
        clearTimeout(target.resizeFlag);
      }
      target.resizeFlag = setTimeout(function () {
        myCharts.resize();
        if (onResize && typeof onResize === 'function') {
          onResize();
        }
        target.resizeFlag = null;
      }, 100);
    }
  }

  render() {
    const {keys} = this.props;
    return (
      <div
        id={`${keys}_drawingBoard`}
        style={{width: '100%', height: '100%'}}/>
    )
  }
}

export default PieChart;

有兴趣的朋友可以关注下option中的graphic属性,和D3比较类似,有时间分享一下用这属性做的图形!!!

    原文作者:machinist
    原文地址: https://segmentfault.com/a/1190000020276939
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞