Echarts官网教程中就有告诉经过各类方式获取Echarts:http://echarts.baidu.com/tutorial.htmljavascript
最简单的方式就是直接引用js文件就o了~html
固然,此次要用的是webpack来进行包管理,因此就要经过webpack来获取Echarts:java
npm install echarts --save
经过webpack获取的ECharts会放在项目的node_modules
目录下,能够直接经过require('echarts')
获得。node
默认使用 require('echarts') 获得的是已经加载了全部图表和组件的 ECharts 包,所以体积会比较大,若是在项目中对体积要求比较苛刻,也能够只按需引入须要的模块。react
官方式这么说的,因此咱们要到https://github.com/ecomfe/echarts/blob/master/index.js去查看能够引入的模块列表,并按需引入。webpack
好比此次我须要画一个饼图,我就须要引入:git
var echarts = require('echarts/lib/echarts') require('echarts/lib/chart/pie') require('echarts/lib/component/title')
咱们先定义一个Component
,ECharts的渲染是须要在这个div有宽高的前提下,因此在这个组件的render()
方法中要有一个div容器来展现ECharts,而且这个div要设置宽高。github
render() { return ( <div className="pie-react"> <div ref="pieChart" style={{width: "200px", height: "200px"}}> </div> </div> ) }
就像平时使用ECharts同样,咱们先是获取数据,而后init
ECharts,而后setOption
,就搞定了~web
initPieChart() { const { data } = this.props let myChart = echarts.init(this.refs.pieChart) let options = this.setOption(data) myChart.setOption(options) } //这是一个最简单的饼图~ setOption(data) { return { title:{ text:"编程语言", left:"center" }, series : [ { name: '比例', type: 'pie', data: data, label: { normal: { formatter: "{d}% \n{b}", } } } ] } }
constructor(props) { super(props) this.setOption = this.setOption.bind(this) this.initChart = this.initChart.bind(this) }
上面已经定义了initPieChart
方法,咱们该在何时用这个方法呢?npm
固然是要在DOM渲染完成了以后啊,而后经过refs去获取这个DOM节点~
也就是componentDidMount
的时候:
componentDidMount() { this.iniChart(); }
componentDidUpdate() { this.iniChart(); }
import Pie from './pie'; const data = [ {value: 2, name: "JavaScript"}, {value: 1, name: "Java"}, {value: 1, name: "HTML/CSS"} ] export default class ComponentBody extends React.Component{ render(){ return( <div className="bodyindex"> <Pie data={data}/> </div> ) } }
完整代码见https://github.com/axuebin/react-echarts-demo/blob/master/src/pie.js