參考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>
)
}
}