章鱼鱼 發表於 2019-7-25 11:03:00

echarts在react项目中的使用

<p><span style="font-size: 16px">数据可视化在前端开发中经常会遇到,万恶的图表,有时候总是就差一点,可是怎么也搞不定。</span></p>
<p><span style="font-size: 16px">别慌,咱们一起来研究。</span></p>
<p><span style="font-size: 16px">引入我就不多说了 <span style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 128, 0, 1)">npm install echarts</span></span></p>
<p><span style="font-size: 16px">对于基础的可视化组件,我一般采用组件封装的方式来使用echarts</span></p>
<p><span style="font-size: 16px">当需要在项目中使用echarts做图表时,可以直接将其封装成一个组件</span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;"><span style="font-size: 14px"> 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 = () =&gt; {
14   const data = this.props.data;
15   var piedata = data.map((item, index) =&gt; {
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} &lt;br/&gt;{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 &lt;div id="main" style={{ width: '100%', height: 311 }} /&gt;;
55   }
56 }

//在需要使用的页面 引入并使用
import IndexPieData from '../';

&lt;IndexPieData data={pieData} height={300}&gt;&lt;/IndexPieData&gt;
</span></pre>
</div>
<p>&nbsp;</p>
<p>echarts一些常用的配置项</p>
<div class="cnblogs_code">
<pre><span style="font-size: 14px"><span style="color: rgba(0, 0, 0, 1)">toolbox工具栏
toolbox: {
  show: </span><span style="color: rgba(0, 0, 255, 1)">true</span>,<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">默认为true</span>
  itemSize: 15,<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">工具栏图标的大小 default: 15</span>
  feature: {   <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">自定义工具按钮,添加其他的</span>
    saveAsImage: { show: <span style="color: rgba(0, 0, 255, 1)">true</span> },<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">保存为图片</span>
    <span style="color: rgba(0, 0, 0, 1)">magicType: {
      type: [</span>'bar','line']    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">设置柱状图,折线图切换</span>
    <span style="color: rgba(0, 0, 0, 1)">},
    dataZoom: {
      show: </span><span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">,         
      yAxisIndex: </span><span style="color: rgba(0, 0, 255, 1)">false</span>   <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">禁止y轴做区域缩放</span>
    <span style="color: rgba(0, 0, 0, 1)">},
    restore: {   </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">添加配置项还原图标工具</span>
      show: <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">
    }
  }
}
yAxis: {
  type: </span>'value'<span style="color: rgba(0, 0, 0, 1)">,
  axisLabel: {
  formatter: </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> (val) {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> val;
  },
  showMinLabel: </span><span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">,
  showMaxLabel: </span><span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">,
  }
}
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">type的值</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">value 数值轴,适用于连续数据</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">category类目轴,适用于离散的类目数据,需要设置data</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">time时间轴 适用于连续的时序数据</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">log对数轴,适用于对数数据<br></span></span></pre>
<pre><span style="font-size: 14px">tooltip:{   //提示框组件</span><br><span style="font-size: 14px">  trigger: 'item',   //数据项图形出发</span><br><span style="font-size: 14px">  formatter: '{b}: {d}%',//设置提示框内容</span><br><span style="font-size: 14px">}</span><br><span style="font-size: 14px">。。。太多了,用的时候再看吧!</span></pre>
</div>
<p>&nbsp;</p>
<p><span style="font-size: 16px">最近一直在使用antd pro进行项目开发,在引入echarts时,一般都是配合表单查询进行使用</span></p>
<p><span style="font-size: 16px">在实际开发中</span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;"><span style="font-size: 14px">//同样对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',];
<br>
export function daysAlertChart(chartData) {

    let dataList = [];
    let currentSubtext = [];
    let dateTime = [];

    chartData.alertDailyMap.forEach((item, idx) =&gt; {
      let alertType = item.alertType;
      console.log(alertType)
      alertType = typeList.indexOf(alertType) &gt; -1 ? formatMessage({ id: `app.alert.${alertType}` }) : alertType;
      
      currentSubtext.push({
            name: alertType
      })
      
      dataList.push({
            name: alertType,
            data: chartData.alertDailyMap.alertCount,
            type: 'bar'
      })
      console.log(dataList)
    });
    chartData.time.forEach((item2, idx2) =&gt; {
      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: {
            width: 1200,
            //left:'30%',
            bottom: '0%',
            data: currentSubtext,
            formatter: val =&gt; {
                return typeList.indexOf(val) &gt; -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;
}
</span></pre>
</div>
<p><span style="font-size: 16px">因为antd pro项目采用dva完成对fetch请求的封装,可以在完成数据请求之后的回调中进行echarts图表的初始化</span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;"><span style="font-size: 14px">//在页面代码中
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 (
  &lt;div id={'daysAlert'} style={{width:'100%', height:'500px'}}&gt;&lt;/div&gt;
)

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)=&gt;{ initChart('daysAlert',alertData,daysAlertChart)}
  })
}<br>///OK!!!</span></pre>
</div>
<p>  </p>
<p>&nbsp;</p><br><br>
来源:https://www.cnblogs.com/luxiaot/p/11242929.html
頁: [1]
查看完整版本: echarts在react项目中的使用