基於echarts 靈活封裝react柱形圖組件

如今各類框架各類庫都很強大,可是也由於功能強大,致使不少配置都過於繁重,真正有用的就那麼幾個,今天就基於echarts封裝一個通用 柱形圖!

想要了解其餘的組件能夠看下我以前封裝的其餘組件有好的思路或者其餘的也會分享出來的;
基於antd封裝橫向拖動時間軸react

通用柱形圖主要包含幾個部分

  1. title展現,xAxis上label的展現;
  2. maxShow, 柱形圖展現最多不該大於12個否則會影響美觀(或者說觀察數據);
  3. UI方面咱們須要支持修改柱形圖的顏色以及柱形的寬度,無數據提示;
  4. 交互方面咱們須要支持最基礎的點擊事件、雙擊事件,返回暫時固定當前點擊的數據部分、全部數據集合以及echarts對象, 除去點擊事件咱們還須要支持resize,以便視口變化的時候,餅圖隨之重繪;
  5. 支持最廣泛使用的toolbox,tooltip等配置;
  6. 須要支持刪除、新增配置(有時候咱們封裝的不夠完美就須要使用者執行配置一下部分);

實現功能

基於以上幾點咱們開始寫代碼:web

componentDidMount週期中接受父組件傳來的屬性,構建最基本的option,在構建option以前咱們先作下關於maxShow的處理;segmentfault

先聲明一個空數據接受處理後的數據


let newChartsData = [];

而後處理maxShow

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]
    }

*這裏注意下,咱們默認是不處理maxShow,也就是說加入父級沒傳那麼默認是所有展現的,在沒有用zoom配置的的前提下,建議maxShow=12是最佳的;具體時間默認12仍是默認不處理要根據使用者處理的數據來定,我處理的數據多數狀況下不會多於12,因此默認不處理;antd

初始化畫板,構建option等操做

let myCharts = echarts.init(document.getElementById(`${idPrefix}_pie`));

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

    _eventType.map(item => {
      myCharts.off(item);
    });
 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
          }
        }]
    };

這當中以及添加了關於無數據的展現代碼,具體實現的方式請看我以前封裝的基於echarts 靈活封裝react餅圖組件這裏就不在重複了;echarts

添加刪除補充配置功能、實例化option

if (deleteOption) {
      deleteOption.map(item => {
        delete option[item]
      });
    } // 刪除函數

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

    myCharts.setOption(option);

添加點擊事件返回值、添加resize 防抖函數

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);
    }

完整代碼

import React, {PureComponent} from 'react';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
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, 支持多種鼠標事件
* 暫時未封裝zoom,zoom等其餘功能可經過 options本身定義添加
* deleteOption: ['title', 'toolbox', 'tooltip', 'graphic'] 包含echarts含有的屬性
*
* */

/*
 * chartsData 格式
 * const barChartsData = {
 *  xAxis: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
 *  data:[10, 52, 200, 334, 390, 330, 220]
 * };
 * 備用顏色:
 * '#13c2c2', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#eb2f96', '#faad14']
 * */
const _eventType = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseup', 'mouseover', 'mouseout', 'globalout', 'contextmenu'];

class BarChart extends PureComponent {

  static propTypes = {
    chartsData: PropTypes.object.isRequired, // 圖形數據
    idPrefix: PropTypes.oneOfType([
      PropTypes.string.isRequired, // 惟一標識區分多個柱形圖,,
      PropTypes.number.isRequired, // 惟一標識區分多個柱形圖,,
    ]),
    getCharts: PropTypes.func, // 把echarts 對象傳出去
    onResize: PropTypes.func, // 全局onResize事件,
    eChartsEvent: PropTypes.func, // 圖形點擊事件, 返回這各圖形的數據以及對應的param,echarts 對象
    barWidth: PropTypes.string, // 柱子的寬度
    bottom: PropTypes.string || PropTypes.number, // 底部距離
    title: PropTypes.string, // 標題欄,名字
    chartColor: PropTypes.string, // 柱形區域顏色
    label: PropTypes.bool, // 是否展現x軸label
    tooltip: PropTypes.bool, // 是否展現tooltip
    options: PropTypes.object, // 修改 更新的想要的配置,直接那eCharts的就能夠
    deleteOption: PropTypes.array, // 刪除不須要的配置
    eventType: PropTypes.oneOf(_eventType), // 事件類型
  };

  static defaultProps = {
    title: '',
    barWidth: '25',
    chartColor: '#1890ff',
    label: false,
    eventType: 'click',
    bottom: '8%',
    tooltip: true
  };

  componentDidMount() {
    const {
      chartsData, idPrefix, getCharts, onResize, title, chartColor,
      label, deleteOption, options, eChartsEvent, eventType, barWidth,
      bottom
    } = this.props;
    let myCharts = echarts.init(document.getElementById(`${idPrefix}_bar`));

    if (getCharts && typeof func === 'function') {
      getCharts(myCharts);
    }
    _eventType.map(item => {
      myCharts.off(item);
    });

    let series = JSON.parse(JSON.stringify(chartsData.data));

    myCharts.clear();

    if (!chartsData.data.length) {
      chartsData.data = [7, 8, 6, 9]
    }

    let option = {
      color: series.length ? chartColor : ['#bfbfbf'],
      title: {
        text: title,
        top: 20,
        x: 'center'
      },
      toolbox: {
        feature: {
          saveAsImage: {
            type: 'png',
            title: '點擊下載',
          }
        },
        top: 13,
        right: 13
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {   // 座標軸指示器,座標軸觸發有效
          type: 'shadow' // 默認爲直線,可選爲:'line' | 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: series.length ? bottom : 40,
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: series.length ? chartsData.xAxis : [],
          axisTick: {
            alignWithLabel: true
          },
          axisLine: {
            lineStyle: {
              color: series.length ? '#333' : '#ccc',
            }
          },
          axisLabel: {
            show: series.length && label,
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          show: series.length,
          splitLine: {
            show: false,
          },
        }
      ],
      series: [
        {
          name: title,
          type: 'bar',
          barWidth,
          data: chartsData.data
        }
      ],
      graphic: series.length
        ? null
        : [{
          type: 'text',
          left: 'center',
          bottom: 15,
          cursor: 'auto',
          style: {
            text: '暫無數據',
            textAlign: 'center',
            fill: '#bfbfbf',
            fontSize: 16,
            stroke: '#bfbfbf',
            lineWidth: 0
          }
        }]
    };

    if (deleteOption) {
      deleteOption.map(item => {
        delete option[item]
      });
    } // 刪除函數

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

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

    myCharts.setOption(option);
    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 {idPrefix} = this.props;

    return (
      <div
        id={`${idPrefix}_bar`}
        style={{width: '100%', height: '100%'}}/>
    )
  }
}

export default BarChart;

再上兩張圖
圖片描述
正常展現的
圖片描述
無數據的展現框架


配色網站

柱形圖默認顏色我選用的是ant圖庫的默認配色,不少小夥伴不知道怎麼配色,那下邊及分享幾個配色的網站(基本都是咱們公司UE嘴裏摳出來的);函數

  1. antd官方色彩-有這一個基本就夠了
  2. Colordot - A color picker for humans
  3. Colourco.de - find your colour palette
  4. Color Scheme Designer 3_高級在線配色器_配色網
  5. Color Hunt - Trendy Color Palettes

若是以爲寫的還能夠,必定要點個贊再走,必定哦~

相關文章
相關標籤/搜索