基於echarts 靈活封裝react餅圖組件

基於echarts 靈活封裝react餅圖組件

這段時間比較忙,沒什麼時間封裝組件庫,同事都不怎麼會使用echarts,今天隨手封裝了一個echart的餅圖, 百十來行的代碼同事用了都說好!
廢話不多說封裝組件之前,首先要考慮我們的組件,都要包含哪些功能;

  1. 窗口隨動,echart的窗口resize,是需要我們自己寫的,這個肯定封裝(注意要做防抖處理);
  2. 每次設置畫布的元素的時候都需要傳入寬高,這也需要,省事嘛;
  3. 鬼知道會不會有事件,所以事件也是肯定要的;
  4. 沒有數據的時候畫布不能空着,加一個暫無數據的展示;
  5. 我在代碼中添加一個名爲options的對象這裏可以補充我沒有封裝的功能,比如需要圖例可以自己定義,傳進去也是一樣的;
  6. 有增加自然就有刪除,刪除的屬性爲deleteOption, 和5一樣都需要判斷是否屬性是否存在,存在則執行,不存在則忽略;

先看看完整體,有興趣您就繼續,沒興趣那就再見來不及握手:
圖片描述圖片描述

看着還是可以的吧!別問我爲什麼沒有圖例,公司多數都是縮略圖,圖例基本用不上,爲了一個不用的多封裝一個功能沒什麼意思!
再看下聲明的propTypes和 defaultProp 儘可能少的使用isRequired (個人意見,免得後續使用者,漏傳就會報錯)
圖片描述
是不是有點多? 還好吧,畢竟這麼靈活!

作用看下注釋就ok了!別說你看不懂啊!s,記住這兩個 一定有,因爲你不知道後面的使用者或不會傳錯,註釋最好也留下,免得被挖墳!

再往下看,在componentDidMount週期中接受props的屬性,組裝自己的option:

圖片描述

注意: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比較類似,有時間分享一下用這屬性做的圖形!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章