在jQuery里面,我会经常用到Echarts统计图,那么就从自己熟悉的地方写,今天在我之前写的React项目里面使用一下折线图。
1:安装Echarts依赖
cnpm install echarts cnpm install --save echarts-for-react
添加完成之后可以看到,package.json
里面已经出现依赖了 。
2:新建一个组件空白组件模板,开始写代码
import React, { Component } from 'react'; class Echarts extends Component { constructor(props) { super(props); //react定义数据 this.state = { } } render() { return ( <div> <h2>我是echarts组件界面</h2> </div> ) } } export default Echarts;
3:在组件里面导入Echarts相关模块组件
引入 ECharts 主模块和引入需要用到的折线图:
// 引入 ECharts 主模块 import echarts from 'echarts/lib/echarts'; // 引入折线图 import 'echarts/lib/chart/line';
4:render()内容
写一个盛放折线图的容器,和平时的写法是一致的
render() { return ( <div id="main" style={{ width: 600, height: 400 }}></div> ); }
5:使用生命周期函数,初始化echarts实例
componentDidUpdate
在组件完成更新后立即调用。在初始化时不会被调用,这里是在Echarts官方网站上复制过来的代码,暂时就写成静态的了,后面会继续写使用axios请求json,渲染在页面的过程。
componentDidMount() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); // 绘制图表 myChart.setOption({ xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [{ data: [520, 932, 901, 1934, 1290, 1330, 1320], type: 'line' }] }); }
参考代码:
import React, { Component } from 'react'; // 引入 ECharts 主模块 import echarts from 'echarts/lib/echarts'; // 引入折线图 import 'echarts/lib/chart/line'; class Echarts extends Component { componentDidMount() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); // 绘制图表 myChart.setOption({ xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [{ data: [520, 932, 901, 1934, 1290, 1330, 1320], type: 'line' }] }); } render() { return ( <div id="main" style={{ width: 600, height: 400 }}></div> ); } } export default Echarts ;
ok,这就可以实现一个图表了。