react中使用ECharts注意的問題

ECharts

ECharts的官網(wǎng)描述:

ECharts,一個使用 JavaScript 實(shí)現(xiàn)的開源可視化庫,可以流暢的運(yùn)行在 PC 和移動設(shè)備上,兼容當(dāng)前絕大部分瀏覽器(IE8/9/10/11,Chrome,F(xiàn)irefox,Safari等),底層依賴矢量圖形庫 ZRender,提供直觀,交互豐富,可高度個性化定制的數(shù)據(jù)可視化圖表。

對比了多款數(shù)據(jù)可視化產(chǎn)品后,對ECharts鐘愛有加,不僅是其豐富的配置項,恰當(dāng)?shù)谋憩F(xiàn)形式,更優(yōu)秀的是相對龐大的社區(qū)群體。
但在由于采用的前端框架為React/UMI/Ant Design,所以在使用過程中遇到了不少問題,經(jīng)歷了一段的填坑期,現(xiàn)在已經(jīng)可以正常使用了。

依賴包

"echarts": "^4.2.1",
"echarts-for-react": "^2.0.15-beta.0",
"echarts-gl": "^1.1.1",
"echarts-liquidfill": "^2.0.5",

其中echarts 和 echarts-for-react 是必須要有的,另外兩個是在使用特定組件的時候需要用到的,echarts-gl 是使用GL組件必須的包,echarts-liquidfill是在做水波圖時必須的包。

使用方式

echarts-for-react針對ECharts提供了專用組件ReactEcharts,只需配置option參數(shù),即可實(shí)現(xiàn)ECharts組件的正常顯示,簡單寫個例子(我用的都是函數(shù)式組件):

import React from 'react';
import ReactEcharts from 'echarts-for-react';

export const EchartExample = (props) => {
  const option = {
    ...
  }
  return (
    <div>
      <ReactEcharts option={option}/>
    </div>
  );
};

其中option就是ECharts的配置項了,具體內(nèi)容可以參照:
ECharts配置項手冊
也可看一些教程:
w3cschool的ECharts教程

舉個簡單的例子:

  const option = {
    backgroundColor: '#001529',
    color: '#0093EE',
    title: {
      top: '2%',
      left: '5%',
      text: title,
      textStyle: {
        color: '#ffffff',
        fontSize: 12,
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
      backgroundColor: ['rgba(255,255,255,0.85)'],
      textStyle: {
        fontSize: 10,
        color: '#353535',
      },
      formatter: function(params) {
        const date = params[0].name;
        const value = params[0].value;
        return `<div align="left">${date}</div><div align="left">${params[0].seriesName}: ${typeof (value) == 'number' ? value.toFixed(2) : "無數(shù)據(jù)"}</div>`;
      },
    },
    grid: {
      left: '7%',
      right: '5%',
      top: '12%',
      bottom: '12%',
    },
    xAxis: [{
      type: 'category',
      data: timeMode?xdata.map((data)=>{return data.split("T")[0].slice(5, 10)}):xdata,
      axisPointer: {
        type: 'shadow',
      },
      axisLine: {
        lineStyle: {
          color: Chart.Config.x_line_color,
        },
      },
      axisLabel: {
        // margin: 26,
        interval: (typeof(xdata)==="undefined"||xdata==null)?2:parseInt((xdata.length/20).toString()),
        rotate: 40,
        textStyle: {
          color: Chart.Config.x_font_color,
          fontSize: 10,
        },
      },
    }],
    yAxis: [{
      axisPointer: {
        show: false,
      },
      splitNumber: 6,
      type: 'value',
      min: 0, //max: 6000,
      axisLabel: {
        textStyle: {
          color: Chart.Config.y_font_color,
          fontSize: '12px',
        },
      },
      axisLine: {
        lineStyle: {
          color: Chart.Config.y_line_color,
        },
      },
      splitLine: {
        lineStyle: {
          color: Chart.Config.split_line_color,
          width: 0,
          type: 'solid',
        },
      },
    },
      {
        axisPointer: {
          show: false,
        },
        splitNumber: 6,
        type: 'value',
        min: 0, //max: 0.6,
        axisLabel: {
          textStyle: {
            color: Chart.Config.y_font_color,
            fontSize: '12px',
          },
        },
        axisLine: {
          lineStyle: {
            color: Chart.Config.y_line_color,
          },
        },
        splitLine: {
          lineStyle: {
            color: Chart.Config.split_line_color,
            width: 1,
            type: 'solid',
          },
        },
      },
    ],
    series: {
      name: title,
      type: 'bar',
      data: ydata,
    },
  };

如何使用echarts的api

echarts-for-react支持echarts api的調(diào)用,其中用到了useRef這個hook來實(shí)現(xiàn),具體的,需要在組件中定義一個ref,然后作為參數(shù)傳遞給ReactEcharts。舉例說明(用的TS,需要變量類型):

export const TestEcharts = () => {
  let trendRef = useRef();
  const option = {
    ...
  }
  return (
    <div>
        <ReactEcharts 
          option={option}
          ref={ref}
        />
    </div>
  )
}

這樣定義之后,在需要調(diào)用api的時候,就像調(diào)用ref方法一樣:

//獲取ref
let eChartsRef = trendRef.current;
//獲取echarts對象
let chart = eChartsRef.getEchartsInstance();

然后,在chart這個對象中,就有echarts提供的api了,報告設(shè)置樣式,圖標(biāo)導(dǎo)出等等。

填坑記錄

前面的內(nèi)容基本在網(wǎng)上一搜都能直接找到答案,但實(shí)際工程應(yīng)用中還是遇到了不少問題,幾個比較耗時間查找的問題記錄如下:

1 修改曲線組件的legend的formatter

具體說就是,比如文字太長,超過多少顯示省略號什么的。

legend: {
    formatter: function (name) {
        return echarts.format.truncateText(name, 40, '14px Microsoft Yahei', '…');
    },
    tooltip: {
        show: true
    }
}

這是需要引入echarts,才能正確執(zhí)行配置。

  //引入echarts 才能使用format
  const echarts = require('echarts/lib/echarts');
2 GL組件的使用

前邊依賴包的列舉已經(jīng)寫上了,需要增加echarts-gl這個依賴。

3 水波圖

目前發(fā)現(xiàn)好像就這里用到過,必須增加echarts-liquidfill這個依賴。

4 漸變色

使用方法是配置color的時候new一個
echarts.graphic.LinearGradient,具體就是這樣:

    itemStyle: {
        normal: {
          barBorderRadius: 30,
          color: new echarts.graphic.LinearGradient(
            0, 0, 0, 1, [{
              offset: 0,
              color: '#00feff',
            },
              {
                offset: 0.5,
                color: '#027eff',
              },
              {
                offset: 1,
                color: '#0286ff',
              },
            ],
          ),
        },
      },

注意的是這里必須導(dǎo)入echarts,否則無法執(zhí)行配置:

import echarts from 'echarts'; 
import 'echarts-gl';

可能不需要導(dǎo)入echarts-gl,因為coding時導(dǎo)入了,沒去掉,忘記是不是有用了……

5 圖表與tab并存時,圖表的導(dǎo)出尺寸異常

這個問題可能使用場景比較少,很少有人用到,所以網(wǎng)上資料不多,但我確實(shí)遇到了,而且還查了很久。
記錄一下:

  • 產(chǎn)生原因:在隱藏tab中的圖表,其默認(rèn)尺寸會為初始狀態(tài),當(dāng)切換顯示時,會恢復(fù)到定義的尺寸。那么如果在其隱藏時,導(dǎo)出圖表的尺寸就依然時初始狀態(tài)。
  • 解決方式:最好可以在保證圖表隱藏前,提前將要獲取的信息通過echarts api取出來,存到對象中,這樣再進(jìn)行其他操作時,無需再調(diào)用echarts api。

持續(xù)更新。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容