react native 使用echarts 是在HTML展示图表,通过webview引入html
安装webview
yarn add react-native-webview
通过下面命令安装
yarn add native-echarts
安装完成之后在node_modules 生成文件夹native-echarts。
这样安装的组件还有问题,
(1)组件中引用的webview是react-native自带的,但是最近几个版本已经没有了,需要引入上面安装的webview
import React, { Component } from 'react';
import { WebView, View } from 'react-native';
import { Container, Echarts } from './components'
将这个组件中所有引入webview的替换为
import WebView from "react-native-webview";
(2)webview引入html 找到
<WebView
ref="chart"
scrollEnabled = {false}
injectedJavaScript = {renderChart(this.props)}
style={{
height: this.props.height || 400,
backgroundColor: this.props.backgroundColor || 'transparent'
}}
scalesPageToFit={Platform.OS !== 'ios'}
originWhitelist={['*']}
source={require('./tpl.html')}
onMessage={event => this.props.onPress ? this.props.onPress(JSON.parse(event.nativeEvent.data)) : null}
/>
改成
<WebView
ref="chart"
scrollEnabled = {false}
injectedJavaScript = {renderChart(this.props)}
style={{
height: this.props.height || 400,
backgroundColor: this.props.backgroundColor || 'transparent'
}}
scalesPageToFit={Platform.OS !== 'ios'}
originWhitelist={['*']}
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}
/>
将tpl.html复制一份放在 项目\android\app\src\main
webview 的source是引入html,在Android端 require此方式不会进行html解析.
基础使用 native-echarts的使用方法基本和网页端的Echarts使用方法一致。组件主要有三个属性:
option (object):图表的相关配置和数据。详见文档:ECharts Documentation width (number):图表的宽度,默认值是外部容器的宽度。 height (number) :图表的高度,默认值是400。
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import Echarts from 'native-echarts';
export default class Index extends Component {
render() {
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
crossStyle: {
color: '#999'
}
}
},
toolbox: {
feature: {
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
legend: {
data: ['Evaporation', 'Temperature']
},
xAxis: [
{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
axisPointer: {
type: 'shadow'
}
}
],
yAxis: [
{
type: 'value',
name: 'Precipitation',
min: 0,
max: 250,
interval: 50,
axisLabel: {
formatter: '{value} ml'
}
},
{
type: 'value',
name: 'Temperature',
min: 0,
max: 25,
interval: 5,
axisLabel: {
formatter: '{value} °C'
}
}
],
series: [
{
name: 'Evaporation',
type: 'bar',
data: [
2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3
]
},
{
name: 'Temperature',
type: 'line',
yAxisIndex: 1,
data: [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]
}
]
};
return (
<Echarts option={option} height={300} />
);
}
}
|