Using Echarts in react-native, echarts experience using WebView encapsulation

Source: Internet
Author: User

1. Problems encountered at work

We in the use of react-native must have encountered a variety of wonderful problems, such as the introduction of echarts time inexplicable error, but Echarts official website obviously tell us can lazy loading, this is because basically JS most native component library does not support react-native, Direct quoting will be reported"undefined is not an object (evaluating ‘ua.match‘)" when importing an incompatible (browser) library.

2. After investigation, React-native's webview can solve this problem.

Sometimes you can use WebView to make up for some of the reactnative built-in components, we can do with HTML, after all, HTML has a wealth of tools to use. For example, in order to display the chart in the Reactnative, the native components are not implemented, the other chart components are based on the REACT-NATIVE-SVG implementation, the display is not satisfactory, if only the display, do not care about the data and dynamic operation of the chart, Here are a few small chart plugins, React-native-pathjs-charts, but if you need to echarts or highchart these rich features, this time HTML has a lot of charting tools to use.

Then we'll teach you how to package your own Echarts components step-by-step.

3. Package Echarts

Suppose I have a local react-native directory as follows

demo/    android/    iOS/    app.js    index.js    packege.json       src/         Components/            chart/        view    ...

We created two new files in the Src/components/chart directory, one called chart.html, one called Chartcomponent.js

Write chart.html as follows:

<! DOCTYPE html>

Then write Chartcomponent.js

Import React, {Component} from ' React '; import {     View,     Text,    ScrollView,    WebView,     Dimensions ,    StyleSheet,    ' react-native 'default  class Selfechart extends Component {      Render () {        return  (            <WebView                  source//              />          )    }  }  

The next step is to introduce your Selfechart component to your page, and if the test file appears, then your webview is effective.

We're starting to transform our chart.html to make it official as we write Echarts.

<! DOCTYPE html>

We need to initialize the Echarts plugin after loading our HTML files and the echarts.min.js inside the file using HTML, this time we need to use WebView injectedjavascript property, but the attribute must be a string of JS, we will first write the JS string to be executed as follows:

/* JS executed after WebView loading external HTML, mainly initializing Echart chart */function renderchart (props) {Const height = ' ${props.height | | 400}px '; const width = props.width? ' ${props.width}px ': ' Auto '; return '    document.getElementById (' main '). Style.height = "${height}";    document.getElementById (' main '). Style.width = "${width}";    var mychart = echarts.init (document.getElementById (' main '));    Mychart.setoption (${toString(props.option)});
This custom message is mainly about monitoring the data changes passed by the WebView component, assuming that the chart data changes, we need to update the Echart option so that the
The chart changes continuously, can realize the real-time monitoring effect, so that does not splash screen
Window.document.addEventListener (' message ', function (e) { var option = Json.parse (e.data); mychart.setoption (option); }); `}

We notice that the above code has a tostring method, mainly to turn the option object into a string, because the Json.stringify () method itself ignores the function properties, so the ToString team Json.stringify made a judgment, the code is as follows

function toString (obj) {Let result = json.stringify (obj, function (key, Val) {        if (typeof val = = = ' function ') {            ret Urn ' ~--demo--~${val}~--demo--~ ';        }        return val;    });    do {        result = result.replace (' \ ' ~--demo--~ ', '). Replace (' ~--demo--~\ "', '). Replace (/\\n/g,"). Replace (/\\\ "/g ,"\"");    } while (Result.indexof (' ~--demo--~ ') >= 0);    return result;}

Everything is ready, and the house starts to introduce the JS code that needs to be executed after the chart.html is loaded within the WebView component.

Export default class Selfechart extends Component {  render () {return (  <webview  source={require ('./ Chart.html ')}//Load HTML resource Injectedjavascript = {Renderchart (this.props)}//Execute JS code inside HTML, must be string/>  );}  }  

option is of course the parent component passed, we can also specify the height and width of the icon display, as well as some other properties, and there are some other auxiliary properties WebView, can help us to optimize the function of the component, Now let's take a look at the complete charcomponent.js code.

Import React, {Component} from ' React '; import {View, Text, ScrollView, WebView, Dimensions, Stylesh  Platform} from ' react-native ';/* Gets the screen width and height of the device */const {width, height} = dimensions.get (' window ');            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," \    "");    } while (Result.indexof (' ~--demo--~ ') >= 0); return result;} /* JS executed after WebView loading external HTML, mainly initializing Echart chart */function renderchart (props) {Const height = ' ${props.height | | 400}px '; const width = props.width?    ' ${props.width}px ': ' Auto '; return ' document.getElementById (' main '). Style.height = "${height}";    document.getElementById (' main '). Style.width = "${width}";    var mychart = echarts.init (document.getElementById (' main ')); MychaRt.setoption (${tostring (Props.option)});    Window.document.addEventListener (' message ', function (e) {var option = Json.parse (e.data);    mychart.setoption (option); }); '}/** * WebView Package react-native Unsupported Plug-in, this package echarts * * This component needs props * option is required, for Echarts configuration property option,  Detailed Configuration Reference official website Echartshttp://echarts.baidu.com/option.html#title * Width not required, for the width of the chart * height does not have to be filled, for the height of the chart * * */export default Class Selfechart 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) {
PostMessage will trigger the message listener method in JS just now, so that the chart refreshes option configuration this.refs.chart.postMessage (json.stringify (option));} Render () {/** The resources loaded under Android are different from iOS and need to be compatible, * is to copy the current chart.html to Android/app/src/main/assets */Const Source = (P Latform. OS = = ' iOS ')? Require ('./chart.html '): {uri: ' file:///android_asset/chart.html '} return (<view style={{width:this.props.width | | Width,flex:1, Height:this.props.height | | 400,}}> <webview ref= "Chart" scrollenabled = {False}style={{height:this.props.height | | 400,backgroundColor: This.props.backgroundColor | | ' Transparent '}} Source={source}//Loaded HTML resource scalespagetofit={platform.os!== ' iOS '}injectedjavascript = {Renderchart ( This.props)}//execute JS code within HTML, must be string/> </View>); } }

So far, our Echar components are packaged, so let's see how we can use them.

Import React, {Component} from ' React '; import {View, text,scrollview} from ' react-native '; import Selfechart from '. /..  /components/chart/chart ' Export default class Listscreen extends React.component {componentdidmount () {/** *                Continuous uninterrupted Refresh icon Demo */SetInterval (() =>{Let data = [5, +, $, ten, Ten, 20].map ((v) =>{ Return Math.random () *v}) var option = {title: {text: ' EC                Harts Getting Started example '}, tooltip: {}, Legend: {data:[' sales ']                }, Xaxis: {data: ["shirts", "sweaters", "chiffon shirts", "trousers", "high Heels", "socks"]},                    YAxis: {}, Series: [{name: ' Sales ', type: ' Bar ',            Data:data}]}; /** Normal chart Refresh by changing the option implementation within the State, the disadvantage is that the component is constantly updated, causing the Chart component to start rendering again, with no coherent effect * in chartcomponentThe Setnewoption method of the polygon encapsulation, * is intended to call mychart.setoption (option) * to reach the non-chattering screen does not update the state refresh chart * */                This.refs.charts.setNewOption (option)},2000)}render () {var option = {title: { Text: ' Echarts Getting Started example '}, tooltip: {}, Legend: {data:[' sales ']}            , Xaxis: {data: ["shirts", "sweaters", "chiffon shirts", "trousers", "high Heels", "socks"]}, YAxis: {},            Series: [{name: ' Sales ', type: ' Bar ', data: [5, 20, 36, 10, 10, 20] }]};return (<scrollview><view style={{flex:1, justifycontent: ' Center ', Alignitems: ' Center '}}> <text>listscreen!</text><selfechart ref= "Charts" Option={option}/></view></scrollview >);}}

  

Using Echarts in react-native, echarts experience using WebView encapsulation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.