React Native使用百度Echarts显示图表

Echarts是百度推出的免费开源的图表组件,功能丰富,涵盖各行业图表。相信很多同学在网页端都使用过。今天我就来介绍下在React Native中如何使用Echarts来显示各种图表。

首先需要在我们的React Native项目中安装native-echarts组件,该组件是兼容IOS和安卓双平台的。

安装

npm installnative-echarts--save

安装完成后在node_modules文件夹下会多出一个文件夹叫native-echarts。目录结构如下图所示: 

基础使用

native-echarts的使用方法基本和网页端的Echarts使用方法一致。组件主要有三个属性:

  1. option (object):图表的相关配置和数据。详见文档:ECharts Documentation

  2. width (number):图表的宽度,默认值是外部容器的宽度。

  3. height (number) :图表的高度,默认值是400。

  4. 4.

示例代码:

 
 
  1. import React, { Component } from 'react';

  2. import {

  3.  AppRegistry,

  4.  StyleSheet,

  5.  Text,

  6.  View

  7. } from 'react-native';

  8. import Echarts from 'native-echarts';

  9. export default class app extends Component {

  10.  render() {

  11.    const option = {

  12.      title: {

  13.          text: 'ECharts demo'

  14.      },

  15.      tooltip: {},

  16.      legend: {

  17.          data:['销量']

  18.      },

  19.      xAxis: {

  20.          data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]

  21.      },

  22.      yAxis: {},

  23.      series: [{

  24.          name: '销量',

  25.          type: 'bar',

  26.          data: [5, 20, 36, 10, 10, 20]

  27.      }]

  28.    };

  29.    return (

  30.      <Echarts option={option} height={300} />

  31.    );

  32.  }

  33. }

  34. AppRegistry.registerComponent('app', () => app);

通过上面的代码我们就可以在React Native里面显示一个图表了。但是我们会发现显示的字体会偏小。我们需要适配下移动端的字体,我们需要在native-echarts文件下找到tpl.html文件,在head里面增加下面一句代码: <metaname="viewport"content="width=device-width, initial-scale=1">这样字体大小就显示正常了。

进阶使用:

在使用图表时,如果我们需要使用图表的点击事件,比如点击柱状图的某个柱子,获取到该柱子的信息,再跳转到详情页面,这该怎么做呢?组件本身是没有这个属性的,需要我们自己修改下代码,传递下消息。具体代码如下:

首先我们需要在renderChart.js文件中把需要的数据注入并传递出来(window.postMessage):

 
 
  1. import echarts from './echarts.min';

  2. import toString from '../../util/toString';

  3. export default function renderChart(props) {

  4.  const height = props.height || 400;

  5.  const width = props.width || 568;

  6.  return `

  7.    document.getElementById('main').style.height = "${height}px";

  8.    document.getElementById('main').style.width = "${width}px";

  9.    var myChart = echarts.init(document.getElementById('main'));

  10.    myChart.setOption(${toString(props.option)});

  11.    myChart.on('click', function (params) {

  12.      var  message = {};

  13.      message.event='click';

  14.      message.seriesName = params.seriesName;

  15.      message.name = params.name;

  16.      window.postMessage(JSON.stringify(message));

  17. });

  18.  `

  19. }

然后在index.js中做处理(handleMessage):

 
 
  1. import React, { Component } from 'react';

  2. import { WebView, View, StyleSheet, Platform } from 'react-native';

  3. import renderChart from './renderChart';

  4. import echarts from './echarts.min';

  5. export default class App extends Component {

  6.  componentWillReceiveProps(nextProps) {

  7.    if(JSON.stringify(nextProps.option) !== JSON.stringify(this.props.option)) {

  8.      this.refs.chart.reload();

  9.    }

  10.  }

  11.  handleMessage = (evt) => {

  12.    const message = JSON.parse(evt.nativeEvent.data)

  13.     this.props.handleMessage(message);

  14.  }

  15.  render() {

  16.    return (

  17.      <View style={{flex: 1, height: this.props.height,width: this.props.width }}>

  18.        <WebView

  19.          ref="chart"

  20.          scrollEnabled = {false}

  21.          injectedJavaScript = {renderChart(this.props)}

  22.          style={{

  23.            height: this.props.height|| 400,

  24.            width: this.props.width || 568,

  25.          }}

  26.          onMessage={this.handleMessage}

  27.          source={require('./tpl.html')}

  28.        />

  29.      </View>

  30.    );

  31.  }

  32. }

最后在使用图表的页面中,修改下代码来接受传递过来的消息: <Echartsoption={option}height={height}width={theme.screenWidth}handleMessage={this.handleMessage}/>在handleMessage方法中就可以写自己的逻辑来处理传递过来数据了。

打包:

如果就这样打包的话,IOS是可以正常打包并显示的。但是在android端打包时会出错。

解决方法:

  • 将index.js中的代码: source={require('./tpl.html')}修改为: source={Platform.OS==='ios'?require('./tpl.html'):{uri:'file:///android_asset/tpl.html'}}


  • 同时将tpl.html文件拷贝到安卓项目下面的app/src/main/assets文件夹中。


在执行完react-native bundle命令后,需要手动将资源文件res/drawable-mdpi中生成的tpl.html文件删除,再执行cd android && ./gradlew assembleRelease命令,这样就能成功打包了。


转载http://mp.weixin.qq.com/s/ooJbommxChEI4idF4HQ7QQ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在React Native使用ECharts,你可以按照以下步骤进行操作: 1. 首先,安装所需的依赖包。在项目的根目录下打开终端,输入以下命令: ``` npm install react-native-webview --save npm install echarts --save ``` 2. 创建一个新的组件,比如`EChartsComponent.js`,并将其添加到你的项目中。在该组件中,你需要导入`react-native-webview`和`echarts`: ```javascript import React from 'react'; import { WebView } from 'react-native-webview'; import echarts from 'echarts'; const EChartsComponent = () => { // 在此处配置你的ECharts图表选项 const option = { // ...ECharts图表配置 }; // 将图表选项转为字符串,并使用webView加载ECharts const chartOption = JSON.stringify(option); return ( <WebView originWhitelist={['*']} source={{ html: `<div id="chart" style="width: 100%; height: 100%;"></div>` }} injectedJavaScript={` var chartDom = document.getElementById('chart'); var myChart = echarts.init(chartDom); var option = ${chartOption}; myChart.setOption(option); `} style={{ flex: 1 }} /> ); }; export default EChartsComponent; ``` 3. 在你的页面中使用`EChartsComponent`组件: ```javascript import React from 'react'; import EChartsComponent from './EChartsComponent'; const App = () => { return ( <EChartsComponent /> ); }; export default App; ``` 这样,你就可以在React Native应用中使用ECharts来绘制图表了。记得根据你的需求在`EChartsComponent.js`中配置图表选项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值