【React】react項目引入echarts插件

參考npm文檔:https://www.npmjs.com/package/echarts-for-react

由於npm上已經有針對react項目出的echarts插件,所以在這裏直接安裝

第一步:npm安裝echarts-for-react
npm install --save echarts-for-react
npm install echarts --save //如果有報錯找不到echarts模塊,需要在安裝一下exharts'
第二步:引入模塊和組件
import echarts from 'echarts' 
import echarts from 'echarts/lib/echarts'
<ReactEcharts option={this.getOption()} />
第三步:參考echarts官網實例添加option參數

參考官網:https://echarts.baidu.com/examples/

getOption =()=> {
    let option = {
        title:{
          text:'用戶騎行訂單'
        },
        tooltip:{   //展示數據
          trigger:'axis'
        },
        xAxis:{
          data:['週一','週二','週三','週四','週五','週六','週日']
        },
        yAxis:{
          type:'value'
        },
        series:[
          {
            name:'訂單量',
            type:'bar',
            data:[1000,2000,1500,3000,2000,1200,800]
          }
        ]
    }
    return option;
  }
注意:由於引入echarts文件太大,所以一般按需引入,完整項目代碼如下:
import React from 'react';
import {Card} from 'antd';
import echartTheme from './../themeLight'
//不是按需加載的話文件太大
//import echarts from 'echarts'
//下面是按需加載
import echarts from 'echarts/lib/echarts'
//導入折線圖
import 'echarts/lib/chart/line';  //折線圖是line,餅圖改爲pie,柱形圖改爲bar
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/markPoint';
import ReactEcharts from 'echarts-for-react';
export default class Line extends React.Component{
  componentWillMount(){
    //主題的設置要在willmounted中設置
    echarts.registerTheme('Imooc',echartTheme);
  }
  getOption =()=> {
    let option = {
      title:{
        text:'用戶騎行訂單',
        x:'center'
      },
      tooltip:{
        trigger:'axis',
      },
      xAxis:{
        data:['週一','週二','週三','週四','週五','週六','週日']
      },
      yAxis:{
        type:'value'
      },
      series:[
        {
          name:'OFO訂單量',
          type:'line',   //這塊要定義type類型,柱形圖是bar,餅圖是pie
          data:[1000,2000,1500,3000,2000,1200,800]
        }
      ]
    }
   return option
  }

  render(){
    return(
      <div>
        <Card title="折線圖表之一">
            <ReactEcharts option={this.getOption()} theme="Imooc"  style={{height:'400px'}}/>
        </Card>

      </div>
    )
  }
}
注意:按需加載是引入node_modules文件夾中的js文件,所以,如果記得改import 'echarts/lib/chart/line'; 折線圖不用改,餅圖和柱形圖line分別改爲pie和bar
完整的代碼可以看一下我上傳在github上的項目https://github.com/topvae/echarts-in-React.git
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章