数据统计图用react怎么做
Echarts图表功能很强大,使用起来也很方便,下面我们就说说怎么在react中使用Echarts。用的前端开发工具是webStorm
1.添加依赖
在webStorm的命令行输入以下语句:
npm install --save echarts-for-react
依赖添加完成后项目的node_modules目录下出现echarts的依赖目录和echarts-for-react的依赖目录
在项目的package.json中出现echarts-for-react的依赖,如图所示:
启动本地服务后会报错,说找不到echarts的依赖,所以如果只执行npm install --save echarts-for-react会报错,可以执行下面的命令
npm install --save echarts-for-react npm install echarts --save
此时项目的package.json会出现两个依赖,如下图所示:
2.在图表页面引入Echarts
import React from 'react'; import ReactEcharts from 'echarts-for-react';
3.echarts的官方图表示例
官方网站:http://echarts.baidu.com/examples.html,提供了很多图表
我们以折线图为例,下图是官方的图表和对应的代码示例:
在react中使用echarts很简单,只需要将option中的代码放到react的getOtion方法中就就OK了,
import React from 'react'; import ReactEcharts from 'echarts-for-react'; const LineMarkerEcharts = React.createClass({ propTypes: { }, getOtion: function() { const option = { title: { text: '未来一周气温变化', subtext: '纯属虚构' }, tooltip: { trigger: 'axis' }, legend: { data:['最高气温','最低气温'] }, toolbox: { show: true, feature: { dataZoom: { yAxisIndex: 'none' }, dataView: {readOnly: false}, magicType: {type: ['line', 'bar']}, restore: {}, saveAsImage: {} } }, xAxis: { type: 'category', boundaryGap: false, data: ['周一','周二','周三','周四','周五','周六','周日'] }, yAxis: { type: 'value', axisLabel: { formatter: '{value} °C' } }, series: [ { name:'最高气温', type:'line', data:[11, 11, 15, 13, 12, 13, 10], markPoint: { data: [ {type: 'max', name: '最大值'}, {type: 'min', name: '最小值'} ] }, markLine: { data: [ {type: 'average', name: '平均值'} ] } }, { name:'最低气温', type:'line', data:[1, -2, 2, 5, 3, 2, 0], markPoint: { data: [ {name: '周最低', value: -2, xAxis: 1, yAxis: -1.5} ] }, markLine: { data: [ {type: 'average', name: '平均值'}, [{ symbol: 'none', x: '90%', yAxis: 'max' }, { symbol: 'circle', label: { normal: { position: 'start', formatter: '最大值' } }, type: 'max', name: '最高点' }] ] } } ] }; return option; }, render: function() { let code = "<ReactEcharts " + " option={this.getOtion()} " + " style={{height: '350px', width: '1000px'}} " + " className='react_for_echarts' />"; return ( <ReactEcharts option={this.getOtion()} style={{height: '350px', width: '1000px'}} className='react_for_echarts' /> ); } }); export default LineMarkerEcharts;
此时,这个图表就成为了我们react中的组件,在项目中需要使用图表的时候直接引入组件就可以了。
更多React相关技术文章,请访问React答疑栏目进行学习!
以上就是数据统计图用react怎么做的详细内容,更多请关注0133技术站其它相关文章!