preface

Recently, I have been working on React-Native, and there is a need to implement line charts, using Ali’s ANTV/F2 visualization library.

Scheme introduction:

  • react-native-webview
  • antv/f2

Use webView to load the local HTML file, and injectJavaScript to load the JS script

steps

  1. newf2chart.html, the file is large, the file address:f2chart.html

In ios, this file with the components in the same directory, in andirod, manual switch files in the android/app/SRC/main/assets/f2chart HTML, if there is no this folder, create a manually.

  1. newf2Chartcomponent
import React, { PureComponent, createRef } from 'react';
import { StyleSheet, Platform } from 'react-native';
import { WebView as RNWebView } from 'react-native-webview';
import renderChart, { changeChartData } from './renderChart';

const source = Platform.select({
  // eslint-disable-next-line global-require
  ios: require('./f2chart.html'),
  android: { uri: 'file:///android_asset/f2chart.html'}});export default class Chart extends PureComponent {

  constructor(props) {
    super(props);
    this.chart = createRef();
  }

  // eslint-disable-next-line react/no-deprecated
  componentWillReceiveProps(nextProps) {
    const { data } = this.props;
    if(data ! == nextProps.data) {this.reload();
      this.chart.current.injectJavaScript(changeChartData(nextProps));
    }
  }

  update = data= > {};

  onMessage = event= > {
    const {
      nativeEvent: { data },
    } = event;
    const { onChange } = this.props;
    const tooltip = JSON.parse(data);
    onChange(tooltip);
  };

  reload = (a)= > {
    this.chart.current.reload();
  };

  onLoadEnd = (a)= > {
    setTimeout((a)= > {
      this.chart.current.injectJavaScript(renderChart(this.props));
    }, 10);
  };

  render() {
    const{ data, ... props } =this.props;
    return (
      <RNWebView
        scrollEnabled={false}
        javaScriptEnabled
        ref={this.chart}
        style={styles.webView}
        injectedJavaScript={renderChart(this.props)}
        source={source}
        onLoadEnd={this.onLoadEnd}
        originWhitelist={[The '*']}onMessage={this.onMessage}
        {. props} / >
    );
  }
}

const styles = StyleSheet.create({
  webView: {
    flex: 1,
    backgroundColor: 'transparent',
  },
});

Copy the code

It’s important to note here that the React-Native WebView has been removed in the latest version of React-Native, so you need to install react-Native WebView

yarn add react-native-webview -S
Copy the code

3. New renderChart. Js

export default function renderChart(props) {
  const { data = [] } = props;
  const chartData = data.map(c= > {
          return {
            ...c,
            date: formatChartDate(c.date), // Process the time in 2020-03-12 12:00:00 format
          };
        })
      

  const lastData = chartData[chartData.length - 1];

  const script = `
  (function(){
    const chart = new F2.Chart({
      id: 'chart',
      pixelRatio: window.devicePixelRatio,
      padding: 'auto',
    });
    chart.source(The ${JSON.stringify(chartData)}, { value: { tickCount: 5, min: 0, ticks: [0, 25, 50, 75, 100], sortable:false }, date: { type: 'timeCat', range: [0, 1], tickCount: 3, } }); chart.tooltip({ showCrosshairs:true, crosshairsStyle: { lineDash: [2] }, alwaysShow:true, showItemMarker: False, background: {radius: 2, fill: 'RGB (229,35,97)', padding: [2, 6]}, tooltipMarkerStyle: {fill: TooltipMarker style radius: 4, lineWidth: 2, stroke: '#d9e5fc',}, onShow: function(ev) { const items = ev.items; const value = items[0].value; items[0].name = null; items[0].value = value>0? '+'+value +' yuan ': '0.00'; }}); chart.axis('value', { label: function label(text, index, total) { const textCfg = { text }; return textCfg; }}); chart.axis('date', { label: function label(text, index, total) { const textArr = text.split('-'); const month = textArr[1]; Const textCfg = {color:'#888B9C', fontSize:'10', text:textArr[0]+ parseInt(month)+' month '}; if (index === 0) { textCfg.textAlign = 'left'; } else if (index === total - 1) { textCfg.textAlign = 'right'; } return textCfg; }}); chart.line({ sortable: false }).position('date*value').shape('smooth') chart.area({ sortable: false }).position('date*value').shape('smooth') chart.render(); const item =The ${JSON.stringify(lastData)}const point = chart.getPosition(item); chart.showTooltip(point); }) (); `;
  return script;
}

Copy the code

Specific configuration can query the official APIf2. Antv. Vision/useful/docs/API…

Use 4.

import F2LineChart from 'F2LineChart'

render(){
    return(
        <View>
            <F2LineChart data=[] />
        </View>)}Copy the code

about

  • This article was first published in React-Native to implement line charts using F2