侧边栏壁纸
博主头像
江祎铭博主等级

不知江月待何人

  • 累计撰写 177 篇文章
  • 累计创建 3 个标签
  • 累计收到 119 条评论
标签搜索

目 录CONTENT

文章目录

react中使用ECharts注意的问题

江祎铭
2023-03-17 / 0 评论 / 0 点赞 / 400 阅读 / 3,909 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2023-03-17,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
广告 广告

ECharts

ECharts的官网描述:

ECharts,一个使用 JavaScript 实现的开源可视化库,可以流畅的运行在 PC 和移动设备上,兼容当前绝大部分浏览器(IE8/9/10/11,Chrome,Firefox,Safari等),底层依赖矢量图形库 ZRender,提供直观,交互丰富,可高度个性化定制的数据可视化图表。

对比了多款数据可视化产品后,对ECharts钟爱有加,不仅是其丰富的配置项,恰当的表现形式,更优秀的是相对庞大的社区群体。
但在由于采用的前端框架为React/UMI/Ant Design,所以在使用过程中遇到了不少问题,经历了一段的填坑期,现在已经可以正常使用了。

依赖包

"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参数,即可实现ECharts组件的正常显示,简单写个例子(我用的都是函数式组件):

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

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

其中option就是ECharts的配置项了,具体内容可以参照:
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) : "无数据"}</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的调用,其中用到了useRef这个hook来实现,具体的,需要在组件中定义一个ref,然后作为参数传递给ReactEcharts。举例说明(用的TS,需要变量类型):

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

这样定义之后,在需要调用api的时候,就像调用ref方法一样:

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

然后,在chart这个对象中,就有echarts提供的api了,报告设置样式,图标导出等等。

填坑记录

前面的内容基本在网上一搜都能直接找到答案,但实际工程应用中还是遇到了不少问题,几个比较耗时间查找的问题记录如下:

1 修改曲线组件的legend的formatter

具体说就是,比如文字太长,超过多少显示省略号什么的。

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

这是需要引入echarts,才能正确执行配置。

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

前边依赖包的列举已经写上了,需要增加echarts-gl这个依赖。

3 水波图

目前发现好像就这里用到过,必须增加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',
              },
            ],
          ),
        },
      },

注意的是这里必须导入echarts,否则无法执行配置:

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

可能不需要导入echarts-gl,因为coding时导入了,没去掉,忘记是不是有用了……

5 图表与tab并存时,图表的导出尺寸异常

这个问题可能使用场景比较少,很少有人用到,所以网上资料不多,但我确实遇到了,而且还查了很久。
记录一下:

  • 产生原因:在隐藏tab中的图表,其默认尺寸会为初始状态,当切换显示时,会恢复到定义的尺寸。那么如果在其隐藏时,导出图表的尺寸就依然时初始状态。
  • 解决方式:最好可以在保证图表隐藏前,提前将要获取的信息通过echarts api取出来,存到对象中,这样再进行其他操作时,无需再调用echarts api。

持续更新。

0
广告 广告

评论区