Home > Article > Web Front-end > Let’s talk about how to use echarts to draw charts in React Native
How to draw charts in React Native? The following article will introduce to you how to use React Native Echarts to develop a real e-commerce data statistics page. I hope it will be helpful to you!
When writing charts related to daily needs, the most used chart library is echarts. The performance of echarts on the web side is quite mature, and the official solution is also provided for the mini program side, but there is no corresponding support for RN. Most of the solutions found on the market are essentially based on webview, and I prefer solutions based on RN. After all, the native experience will be better than the web one.
So we released @wuba/react-native-echarts to meet the demand. Those who are interested in the implementation principle can read here.
Next I will use @wuba/react-native-echarts to make an application in an actual project. The screenshot is as follows:
Set up the RN development environment locally. The construction process can be found online, so I won’t go into details.
Because it is a trial, I used expo to newly initialize an RN project called TestApp.
npx create-expo-app TestApp
Use the command line to generate the package ios android app package. It is recommended to use the simulator here for ios (no certificate required). For Android, I connected it to a real machine
yarn android yarn ios
After generating the package, if the phone sees that the application has been installed, it means success.
yarn add @wuba/react-native-echarts echarts yarn add @shopify/react-native-skia yarn add react-native-svg
Note that if you are installing in an existing project, you must create a new package after the installation is completed, otherwise An error will be reported if native dependencies are missing;
@wuba/react-native-echarts supports two rendering modes (Skia and Svg) , use it first Skia Try a simple chart. It can be roughly divided into these small steps:
The specific code is as follows:
import { useRef, useEffect } from 'react'; import { View } from 'react-native'; /** * 一、引入echarts依赖,这里先试下折线图 */ import * as echarts from 'echarts/core'; import { LineChart } from 'echarts/charts'; import { GridComponent } from 'echarts/components'; import { SVGRenderer, SkiaChart } from '@wuba/react-native-echarts'; /** * 二、注册需要用到的组件 * SVGRenderer: 是必须注册的 * LineChart: 因为用的折线图,所以要引入LineChart(如果不知道该引入哪些组件,就直接看报错,报错说缺什么就加什么) * GridComponent: 这个就是报错的时候提示,然后我加的hhh */ echarts.use([SVGRenderer, LineChart, GridComponent]); export default () => { const skiaRef = useRef(null); // Ref用于保存图表实例 useEffect(() => { /** * 四、图表配置 */ const option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], }, yAxis: { type: 'value', }, series: [ { data: [150, 230, 224, 218, 135, 147, 260], type: 'line', }, ], }; let chart; if (skiaRef.current) { /** * 五、初始化图表,指定下宽高 */ chart = echarts.init(skiaRef.current, 'light', { renderer: 'svg', width: 400, height: 400, }); chart.setOption(option); } /** * 六、页面关闭后要销毁图表实例 */ return () => chart?.dispose(); }, []); return ( <View className='index'> <SkiaChart ref={skiaRef} /> </View> ); };
After writing, shake the phone and it will appear when reloading the bundle Error report:
ERROR Invariant Violation: requireNativeComponent: "SkiaDomView" was not found in the UIManager.
Googled it and said it needed to bedowngraded solve. In fact, it needs to correspond to the expo version. When installing dependencies, there will be a prompt similar to this. Just install the prompted version.
So I downgraded the version according to the prompts. :
@shopify/react-native-skia@0.1.157 react-native-svg@13.4.0
After rebuilding the app, it was loaded, and the needle did not poke; (Android covered the point, it seems that it should adapt to the screen width)
iOS | Android |
---|---|
iOS | Android |
---|---|
效果不错,不过每次使用都要把一堆东西引进去好烦,先简单封装下吧
import { useRef, useEffect } from 'react'; import * as echarts from 'echarts/core'; import { BarChart, LineChart, PieChart } from 'echarts/charts'; import { DataZoomComponent, GridComponent, LegendComponent, TitleComponent, ToolboxComponent, TooltipComponent, } from 'echarts/components'; import { SVGRenderer, SvgChart as _SvgChart, SkiaChart as _SkiaChart, } from '@wuba/react-native-echarts'; import { Dimensions } from 'react-native'; // 注册需要用到的组件 echarts.use([ DataZoomComponent, SVGRenderer, BarChart, GridComponent, LegendComponent, ToolboxComponent, TooltipComponent, TitleComponent, PieChart, LineChart, ]); // 图表默认宽高 const CHART_WIDTH = Dimensions.get('screen').width; // 默认用手机屏幕宽度 const CHART_HEIGHT = 300; const Chart = ({ option, onInit, width = CHART_WIDTH, height = CHART_HEIGHT, ChartComponent, }) => { const chartRef = useRef(null); useEffect(() => { let chart; if (chartRef.current) { chart = echarts.init(chartRef.current, 'light', { renderer: 'svg', width, height, }); option && chart.setOption(option); onInit?.(chart); } return () => chart?.dispose(); }, [option]); return <ChartComponent ref={chartRef} />; }; const SkiaChart = (props) => <Chart {...props} ChartComponent={_SkiaChart} />; const SvgChart = (props) => <Chart {...props} ChartComponent={_SvgChart} />; // 对外只暴露这哥俩就行 export { SkiaChart, SvgChart };
封装好了,咱就写个多图表同时使用的页面看看效果。这里写了个“电商数据分析”页面,分别有折线图、柱状图、饼图。下方是主要代码,用的 svg 模式,详细代码见这里。
// 页面代码 import { SkiaChart } from '../../components/Chart'; import { ScrollView, Text, View } from 'react-native'; import { StatusBar } from 'expo-status-bar'; import { useCallback, useEffect, useState } from 'react'; import { defaultActual, lineOption, salesStatus, salesVolume, userAnaly, getLineData, } from './contants'; import styles from './styles'; // 开启图表loading const showChartLoading = (chart) => chart.showLoading('default', { maskColor: '#305d9e', }); // 关闭图表loading const hideChartLoading = (chart) => chart.hideLoading(); export default () => { const [actual, setActual] = useState(defaultActual); // 记录实时数据 useEffect(() => { // 假设循环请求数据 const interv = setInterval(() => { const newActual = []; for (let it of actual) { newActual.push({ ...it, num: it.num + Math.floor((Math.random() * it.num) / 100), }); } setActual(newActual); }, 200); return () => clearInterval(interv); }, [actual]); const onInitLineChart = useCallback((myChart) => { showChartLoading(myChart); // 模拟数据请求 setTimeout(() => { myChart.setOption({ series: getLineData, }); hideChartLoading(myChart); }, 1000); }, []); const onInitUserChart = useCallback((myChart) => { // 模拟数据请求,跟onInitLineChart类似 }, []); const onInitSaleChart = useCallback((myChart) => { // 模拟数据请求,跟onInitLineChart类似 }, []); const onInitStatusChart = useCallback((myChart) => { // 模拟数据请求,跟onInitLineChart类似 }, []); const chartList = [ ['订单走势', lineOption, onInitLineChart], ['用户统计', userAnaly, onInitUserChart], ['各品类销售统计', salesVolume, onInitSaleChart], ['订单状态统计', salesStatus, onInitStatusChart], ]; return ( <ScrollView style={styles.index}> <StatusBar style='light' /> <View> <View style={styles.index_panel_header}> <Text style={styles.index_panel_title}>实时数据</Text> </View> <View style={styles.index_panel_content}> {actual.map(({ title, num, unit }) => ( <View key={title} style={styles.sale_item}> <View style={styles.sale_item_cell}> <Text style={styles.sale_item_text}>{title}</Text> </View> <View style={[styles.sale_item_cell, styles.num]}> <Text style={styles.sale_item_num}>{num}</Text> </View> <View style={[styles.sale_item_cell, styles.unit]}> <Text style={styles.sale_item_text}>{unit}</Text> </View> </View> ))} </View> </View> {chartList.map(([title, data, callback]) => ( <View key={title}> <View style={styles.index_panel_header}> <Text style={styles.index_panel_title}>{title}</Text> </View> <View style={styles.index_panel_content}> <SkiaChart option={data} onInit={callback} /> </View> </View> ))} </ScrollView> ); };
重新加载 bundle,看看效果图
iOS | Android |
---|---|
渲染出来后,iOS 上交互很丝滑,安卓上交互时感觉偶尔会有卡顿(不会是因为我手机太差吧…)。
再换 Skia 模式看看
emmm 虽然可以,但是好像中文不能正常显示,安卓上中文都没有显示,iOS 则是乱码。看了下文档,目前 skia 在安卓端还不支持中文,在 iOS 端可以通过设置字体为 'PingFang SC'显示中文,比如:
const option = { title: { text: '我是中文', textStyle: { fontFamily: 'PingFang SC', // 指定字体类型 }, }, };
但是每个显示中文的地方都要设置字体……那还是先用 svg 吧,我懒。
使用了一段时间后,我总结了下:
The above is the detailed content of Let’s talk about how to use echarts to draw charts in React Native. For more information, please follow other related articles on the PHP Chinese website!