在react-native项目中难免会遇到到图表类的需求,这时一个好的第三方会让我们事半功倍,大神开源了一个# react-native-echarts
可以直接调用百度的ECharts组件,非常不错。但是在使用过程中遇到一些问题。
1.修改index文件
修改 native-echarts 下 src 下 components 下 Echarts 下的 index.js,使用如下的文件进行替换原index.js文件
import React, { Component } from 'react';
import { WebView, View, StyleSheet, Platform, ScrollView } from 'react-native';
import renderChart from './renderChart';
import echarts from './echarts.min';
export default class App extends Component {
// 预防过渡渲染
shouldComponentUpdate(nextProps, nextState) {
const thisProps = this.props || {}
nextProps = nextProps || {}
if (Object.keys(thisProps).length !== Object.keys(nextProps).length) {
return true
}
for (const key in nextProps) {
if (JSON.stringify(thisProps[key]) != JSON.stringify(nextProps[key])) {
return true
}
}
return false
}
componentWillReceiveProps(nextProps) {
if(nextProps.option !== this.props.option) {
// this.refs.chart.reload();
// 解决数据改变时页面闪烁的问题
this.refs.chart.injectJavaScript(renderChart(nextProps))
}
}
render() {
return (
<ScrollView style={{flex: 1, height: this.props.height || 400,}}>
<WebView
ref="chart"
scrollEnabled = {false}
injectedJavaScript = {renderChart(this.props)}
style={{
height: this.props.height || 400,
backgroundColor: this.props.backgroundColor || 'transparent'
}}
scalesPageToFit={Platform.OS === 'android' ? true : false}
source={Platform.OS==='ios' ? require('./tpl.html'):{uri:'file:///android_asset/tpl.html'}}
onMessage={event => this.props.onPress ? this.props.onPress(JSON.parse(event.nativeEvent.data)) : null}
originWhitelist={['*']}
/>
</ScrollView>
);
}
}
2. 拷贝tpl.html文件
注意问题: 还需要将native-echarts下的tpl.html文件放到Android项目的assest目录下:
如果src项目中没有assest目录,就新建一个就行了。
当然也可以直接使用这个组件,已经修复此问题
https://github.com/wayne214/react-native-echarts
3.native echarts 打包release tooltip formatter 中文被转化为Unicode的解决方法
打开node_modules->native-echarts->src->util->toStrings
export default function toString(obj) {
let result = JSON.stringify(obj, function(key, val) {
if (typeof val === 'function') {
return `~--demo--~${val}~--demo--~`;
}
return val;
});
do {
result = result.replace('\"~--demo--~', '').replace('~--demo--~\"', '').replace(/\\n/g, '').replace(/\\\"/g,"\"");//最后一个replace将release模式中莫名生成的\"转换成"
} while (result.indexOf('~--demo--~') >= 0);
// 添加此行把unicode转为中文(否则formatter函数中含有中文在release版本中显示不出来)
result = unescape(result.replace(/\\u/g, "%u"));
return result;
}