React Native使用百度Echarts显示图表的示例代码(2)
然后在index.js中做处理(handleMessage):
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命令,这样就能成功打包了。
Q1
当数据量比较大的时候,x轴的数据不显示。这个是echarts自己的一个功能,解决办法是设置xAxis-axisLabel-interval为0即可。
Q2
面积折线图中面积颜色“不正“,也就是说和设置的颜色对不上。这个可能是react-native-echarts组件封装的问题,解决办法是设置areaStyle-normal-shadowColor为'#ffffff',同理可以设置lineStyle等。
Q3
打release包的时候报错了,
\android\app\src\main\res\drawable-mdpi\node_modules_nativeecharts_src_components_echarts_tpl.html
Error:Error: The file name must end with .xml or .png
原因:
release打包的时候把node_modules_nativeecharts_src_components_echarts_tpl.html打到了drawable下,这是不行的,要放到assets下。
解决办法是
另外,release版本只能使用uri加载资源,android把tpl.html文件放在android/app/src/main/assets文件里,使用uri:'file:///android_asset/tpl.html'这个地址加载,ios在项目目录下建个文件夹,把tpl文件放里面去,使用uri:'文件名/tpl'加载。