zoukankan      html  css  js  c++  java
  • echarts在react项目中的使用

    数据可视化在前端开发中经常会遇到,万恶的图表,有时候总是就差一点,可是怎么也搞不定。

    别慌,咱们一起来研究。

    引入我就不多说了 npm install echarts

    对于基础的可视化组件,我一般采用组件封装的方式来使用echarts

    当需要在项目中使用echarts做图表时,可以直接将其封装成一个组件

     1 import React, { Component } from 'react';
     2 
     3 // 引入 ECharts 主模块
     4 import echarts from 'echarts/lib/echarts';
     5 // 引入环形图
     6 import 'echarts/lib/chart/pie';
     7 // 引入提示框和标题组件
     8 import 'echarts/lib/component/tooltip';
     9 import 'echarts/lib/component/title';
    10 import 'echarts/lib/component/visualMap';
    11 
    12 export default class IndexPieData extends Component {
    13   initCharts = () => {
    14     const data = this.props.data;
    15     var piedata = data.map((item, index) => {
    16       return {
    17         value: item.y,   //value和name是echarts规定的,呜呜呜
    18         name: item.x,
    19       };
    20     });
    21     // 基于准备好的dom,初始化echarts实例
    22     var myChart = echarts.init(document.getElementById('main'));
    23     // 绘制图表
    24     myChart.setOption({
    25       tooltip: {
    26         trigger: 'item',
    27         // formatter: "{a} <br/>{b}: {c} ({d}%)"
    28         formatter: '{b}:   {d}%',
    29       },
    30       series: [
    31         {
    32           name: '设备占比数量',
    33           type: 'pie',
    34           radius: ['50%', '60%'],
    35           label: {
    36             formatter: '{b}:{d}%',
    37             textStyle: {
    38               color: '#000000',
    39               fontSize: 12,
    40             },
    41           },
    42           data: piedata,
    43         },
    44     });
    45   };
    46 
    47   componentDidMount() {
    48     this.initCharts();
    49   }
    50   componentDidUpdate() {  //当图表切换的时候,重新执行
    51     this.initCharts();
    52   }
    53   render() {
    54     return <div id="main" style={{  '100%', height: 311 }} />;
    55   }
    56 }
    
    //在需要使用的页面 引入并使用
    import IndexPieData from '../';
    
    <IndexPieData data={pieData} height={300}></IndexPieData>
    

    echarts一些常用的配置项

    toolbox工具栏
    toolbox: {
      show: true,  //默认为true
      itemSize: 15,  //工具栏图标的大小 default: 15
      feature: {   //自定义工具按钮,添加其他的
        saveAsImage: { show: true },  //保存为图片
        magicType: {
          type: ['bar','line']    //设置柱状图,折线图切换
        },
        dataZoom: {
          show: true,          
          yAxisIndex: false     //禁止y轴做区域缩放
        },
        restore: {     //添加配置项还原图标工具
          show: true
        }
      }
    }
    yAxis: {
      type: 'value',
      axisLabel: {
      formatter: function (val) {
        return val;
      },
      showMinLabel: true,
      showMaxLabel: true,
      }
    }
    //type的值
    //value 数值轴,适用于连续数据
    //category  类目轴,适用于离散的类目数据,需要设置data
    //time  时间轴 适用于连续的时序数据
    //log  对数轴,适用于对数数据
    tooltip:{   //提示框组件
      trigger: 'item', //数据项图形出发
      formatter: '{b}: {d}%', //设置提示框内容
    }
    。。。太多了,用的时候再看吧!

    最近一直在使用antd pro进行项目开发,在引入echarts时,一般都是配合表单查询进行使用

    在实际开发中

    //同样对echarts代码进行封装
    
    daysAlertChart.js
    // 引入 ECharts 主模块
    import echarts from 'echarts/lib/echarts';
    import moment from 'moment';
    import { formatMessage, FormattedMessage } from 'umi/locale';
    
    const typeList = ['red_alert', 'yellow_alert', 'offline', 'expired', 'suspicious', 'sample_placement_error', 'sample_expired', 'sample_inventory', 'task_incomplete',];
    
    export function daysAlertChart(chartData) { let dataList = []; let currentSubtext = []; let dateTime = []; chartData.alertDailyMap.forEach((item, idx) => { let alertType = item.alertType; console.log(alertType) alertType = typeList.indexOf(alertType) > -1 ? formatMessage({ id: `app.alert.${alertType}` }) : alertType; currentSubtext.push({ name: alertType }) dataList.push({ name: alertType, data: chartData.alertDailyMap[idx].alertCount, type: 'bar' }) console.log(dataList) }); chartData.time.forEach((item2, idx2) => { dateTime.push( moment(item2).format('YYYY-MM-DD'), ) }); let option = { color: ['#f5222d', '#faad14', '#d9d9d9', '#1890ff', '#4d4dff', '#32cd99'], tooltip: { show: true, trigger: 'axis', axisPointer: { type: 'shadow' } }, legend: { 1200, //left:'30%', bottom: '0%', data: currentSubtext, formatter: val => { return typeList.indexOf(val) > -1 ? formatMessage({ id: `app.alert.${val}` }) : val } }, toolbox: { show: true, right: 5, top: 10, feature: { magicType: { show: true, type: ['bar', 'line'] }, //实现柱状图和折线图的切换 dataZoom: { show: true, yAxisIndex: false }, restore: { show: true }, saveAsImage: { show: true } } }, grid: { left: '4%', right: '4%', bottom: '5%', containLabel: true }, xAxis: { type: 'category', data: dateTime, }, yAxis: { type: 'value', axisLabel: { formatter: function (val) { return val; }, showMinLabel: true, showMaxLabel: true, }, }, series: dataList }; return option; }

    因为antd pro项目采用dva完成对fetch请求的封装,可以在完成数据请求之后的回调中进行echarts图表的初始化

    //在页面代码中
    import  {echartsDemo} from '../';
    // 引入 ECharts 主模块
    import echarts from 'echarts/lib/echarts';
    // 引入图表组件
    import 'echarts/lib/chart/line';
    import 'echarts/lib/chart/bar';
    // 引入提示框和标题组件
    import 'echarts/lib/component/tooltip';
    import 'echarts/lib/component/legend';
    import 'echarts/lib/component/toolbox';
    import 'echarts/lib/component/grid';
    import 'echarts/lib/component/dataZoom';
    return (
      <div id={'daysAlert'} style={{'100%', height:'500px'}}></div>
    )
    
    function initChart(domId,data,func) {
      let dom = document.getElementById(domId);
      if (dom) {
        let myChart = echarts.init(dom);
        let option = func(data);
        myChart.setOption(option,true);
      }
    }
    
    componentDidMount() {
      this.props.dispatch({
        type: 'statistics/fetchAlertCountData',
        payload: {
          startTime: startTime,
          endTime: endTime
        },
        //callback需要在对应的models请求接口时,进行传参callback
        //并设置 if(callback) callback(res.data)
        callback: (alertData)=>{ initChart('daysAlert',alertData,daysAlertChart)}
      })
    }
    ///OK!!!

      

  • 相关阅读:
    Effective C++学习笔记之explicit
    腾讯面试经验2
    腾讯面试经验
    值类型和引用类型的区别,struct和class的区别
    【转载】固态硬盘的S.M.A.R.T详解
    SSD的传输总线、传输协议、传输接口
    坏块管理(Bad Block Management,BBM)
    脱离SVN的控制
    Func的介绍
    简单AOP
  • 原文地址:https://www.cnblogs.com/luxiaot/p/11242929.html
Copyright © 2011-2022 走看看