React Native使用百度Echarts显示图表

本文原创首发于公众号:ReactNative开发圈html

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

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

安装

npm install native-echarts --saveandroid

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

image.png

基础使用

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

  1. option (object):图表的相关配置和数据。详见文档:ECharts Documentation
  2. width (number):图表的宽度,默认值是外部容器的宽度。
  3. height (number) :图表的高度,默认值是400。

示例代码:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
import Echarts from 'native-echarts';

export default class app extends Component {
  render() {
    const option = {
      title: {
          text: 'ECharts demo'
      },
      tooltip: {},
      legend: {
          data:['销量']
      },
      xAxis: {
          data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
      },
      yAxis: {},
      series: [{
          name: '销量',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
      }]
    };
    return (
      <Echarts option={option} height={300} />
    );
  }
}

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

image.png

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

进阶使用:

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

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

import echarts from './echarts.min';
import toString from '../../util/toString';

export default function renderChart(props) {
  const height = props.height || 400;
  const width = props.width || 568;
  return `
    document.getElementById('main').style.height = "${height}px";
    document.getElementById('main').style.width = "${width}px";
    var myChart = echarts.init(document.getElementById('main'));
    myChart.setOption(${toString(props.option)});
    myChart.on('click', function (params) {
      var  message = {};
      message.event='click';
      message.seriesName = params.seriesName;
      message.name = params.name;
      window.postMessage(JSON.stringify(message));
 });
  `
}

而后在index.js中作处理(handleMessage):echarts

import React, { Component } from 'react';
import { WebView, View, StyleSheet, Platform } from 'react-native';
import renderChart from './renderChart';
import echarts from './echarts.min';

export default class App extends Component {
  componentWillReceiveProps(nextProps) {
    if(JSON.stringify(nextProps.option) !== JSON.stringify(this.props.option)) {
      this.refs.chart.reload();
    }
  }
  handleMessage = (evt) => {
    const message = JSON.parse(evt.nativeEvent.data)
     this.props.handleMessage(message);
  }
  render() {
    return (
      <View style={{flex: 1, height: this.props.height,width: this.props.width }}>
        <WebView
          ref="chart"
          scrollEnabled = {false}
          injectedJavaScript = {renderChart(this.props)}
          style={{
            height: this.props.height|| 400,
            width: this.props.width || 568,
          }}
          onMessage={this.handleMessage}
          source={require('./tpl.html')}
        />
      </View>
    );
  }
}

最后在使用图表的页面中,修改下代码来接受传递过来的消息:
<Echarts option={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命令,这样就能成功打包了。

举手之劳关注个人微信公众号:ReactNative开发圈

image.png

相关文章
相关标签/搜索