一. 依赖
https://github.com/wuba/react-native-echarts
# echarts官方包
yarn add @wuba/react-native-echarts echarts
# react-native 对 svg 和 skia 的渲染依赖包
yarn add @shopify/react-native-skia
yarn add react-native-svg
# 用于实现点击交互, 只需要静态图表的话可以不安
yarn add react-native-gesture-handler
二. 使用方式
- 导入依赖 和 注册echarts内部组件
此处只写出了 echarts 需要用到的部分资源, 其他资源自行按需导入.
// 以下两种渲染方式可以根据需要二选一, 不必两者都导入
import SvgChart, { SVGRenderer } from '@wuba/react-native-echarts/svgChart';
import SkiaChart, { SVGRenderer } from '@wuba/react-native-echarts/skiaChart';
import * as echarts from 'echarts/core';
// 需要渲染的图表类型
import { BarChart, LineChart, PieChart } from 'echarts/charts';
// echarts 的标签、图例等组件, 与option的内容有关, 可以根据报错信息补充导入
import {
TitleComponent,
ToolboxComponent,
TooltipComponent,
GridComponent,
LegendComponent,
VisualMapComponent
} from 'echarts/components';
// 从 echarts/components 导入的组件需要注册后才能生效.
echarts.use([TitleComponent, TooltipComponent, GridComponent, SVGRenderer, ... ])
- 创建实例
以 svg 渲染方式为例. 创建图表实例的方式与网页端没有差别.
function SvgComponent() {
// 获取节点
const svgRef = useRef(null);
// 图表配置
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',
},
],
};
useEffect(() => {
let chart;
if (svgRef.current) {
// 创建图表
chart = echarts.init(svgRef.current, 'light', {
renderer: 'svg',
width: E_WIDTH,
height: E_HEIGHT,
});
// 写入配置
chart.setOption(option);
}
// 销毁图表
return () => chart?.dispose();
}, [option]);
return <SvgChart ref={svgRef} />;
}
- 让图表支持点击等交互
在图表组件上, 增加useRNGH属性.
使用 react-native-gesture-handler 中的 GestureHandlerRootView组件, 包裹图表组件.
import { GestureHandlerRootView } from 'react-native-gesture-handler';
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center',}}>
<SvgChart ref={svgRef} useRNGH />
</View>
</GestureHandlerRootView>
)