React Native 使用native-echarts图表组件

丁雅惠
2023-12-01

 

1、安装 yarn add native-echarts

2、导入包  import Echarts from 'native-echarts';

3、使用示例

const option = {
    tooltip: {
        trigger: 'axis'
    },
    toolbox: {
        show: false,
        feature: {
            mark: {show: true},
            dataView: {show: true, readOnly: false},
            magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
            restore: {show: true},
            saveAsImage: {show: true}
        }
    },
    calculable: true,
    xAxis: [
        {
            type: 'category',
            boundaryGap: false,
            data: ['10/06', '11/06', '12/06', '13/06', '14/06', '15/06', '25/12']
        }
    ],
    yAxis: [
        {
            type: 'value'
        }
    ],
    series: [
        {
            name: 'profit',
            type: 'line',
            smooth: true,
            itemStyle: {normal: {areaStyle: {type: 'default'}}},
            data: [800, 480, 270, 590, 780, 860, 840]
        }
    ]
};

 

<Echarts
    option={option}
    height={screenHeith * 0.5}
    width={screenWidth}
/>

具体使用文档可参考ECharts官网https://echarts.baidu.com/echarts2/doc/example.html

4、Android端问题

模拟器上显示不出来,真机上测试可以显示,需要修改配置

01、将tpl.html复制到android\app\src\main\assets目录下,tpl.html文件在node_modules\native-echarts\src\components\Echartsassets路径下。

02、修改node_modules\native-echarts\src\components\Echarts目录中的index.js文件:

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 {

  constructor(props) {
    super(props);
    this.setNewOption = this.setNewOption.bind(this);
  }
  

  componentWillReceiveProps(nextProps) {
    if(nextProps.option !== this.props.option) {
      this.refs.chart.reload();
    }
  }

  setNewOption(option) {
    this.refs.chart.postMessage(JSON.stringify(option));
  }

  render() {
    return (
      <View 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 !== '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}
        />
      </View>
    );
  }
}

 

主要修改的时这一行source={Platform.OS === 'ios' ? require('./tpl.html') : {uri:'file:///android_asset/tpl.html'}},根据平台加载不同路径下的tpl.html文件

 类似资料: