如何使用动态工具提示构建React Native图表

鞠鸿雪
2023-12-01

by Vikrant Negi

通过Vikrant Negi

如何使用动态工具提示构建React Native图表 (How to build React Native charts with dynamic tooltips)

Creating charts, be it on the web or on mobile apps, has always been an interesting and challenging task especially in React Native. It’s difficult to find a suitable library that can meet your functional and design needs at the same time. You can try to make your own charts, but that often comes with the overhead of learning and implementing things from scratch.

无论是在Web上还是在移动应用程序上创建图表,一直都是一项有趣且具有挑战性的任务,尤其是在React Native中。 很难找到可以同时满足您的功能和设计需求的合适的库。 您可以尝试制作自己的图表,但这通常伴随着从头开始学习和实现事物的开销。

If you are a beginner like I am, you probably want to use an existing charts library. And given how young the React Native community is, you have very few options available to you to implement and customize charts.

如果您像我一样是初学者,则可能要使用现有的图表库。 考虑到React Native社区还很年轻,您几乎没有可用的实现和自定义图表的选项。

问题陈述 (Problem Statement)

Before starting our journey deep into the woods, I would like to introduce you to our problem statement.

在开始深入森林之前,我想向您介绍我们的问题陈述。

In this tutorial, we are going to draw an area chart and add a circular marker at each of the data points which can further be tapped to show a tooltip containing x and y coordinate values.

在本教程中,我们将绘制一个面积图,并在每个数据点处添加一个圆形标记,可以进一步点击以显示包含x和y坐标值的工具提示。

To solve this problem, I did some research on some existing React Native libraries and narrowed it down two of them, react-native-charts-wrapper, and react-native-svg-charts.

为了解决这个问题,我对一些现有的React Native库进行了一些研究,并将其范围缩小到两个, react-native-charts-wrapperreact-native-svg-charts

React本机图表包装 (React Native Charts Wrapper)

Our first contender, react-native-charts-wrapper is a React Native wrapper of popular Native charting library MPAndroidChart and Charts.

我们的第一个竞争者react-native-charts-wrapper是流行的本机图表库MPAndroidChartCharts的React Native包装器。

This library is highly configurable, and since it uses the native chart libraries it provides silky smooth transitions and touch support. It also has tons of examples of use cases on its Github repo.

该库是高度可配置的,并且由于它使用本机图表库,因此可提供柔滑的平滑过渡和触摸支持。 它在Github仓库上也有大量的用例示例。

In the beginning, it was my preferred choice given its performance and customization. It has a very long and specific installation guide, following which I was able to install and run it on both iOS and Android devices.

刚开始,考虑到它的性能和定制性,这是我的首选。 它有一个非常长且特定的安装指南,随后我能够在iOS和Android设备上安装并运行它。

Everything seems to be working smoothly on Android. However, when I tried to create an iOS build, it gave me an error. After countless hours of searching through GitHub issues and Google, I decided against it.

一切似乎在Android上都能正常运行。 但是,当我尝试创建iOS版本时,它给了我一个错误。 经过数小时的搜索GitHub问题和Google的搜索后,我决定反对它。

React本机SVG图表 (React Native SVG Charts)

After giving up on react-native-charts-wrapper this was the next best solution available that I could find.

放弃了react-native-charts-wrapper这是我能找到的下一个最佳解决方案。

react-native-svg-charts uses react-native-svg under the hood to render charts. It also has tons of examples featuring many use cases.

react-native-svg-charts使用引擎盖下的react-native-svg来绘制图表。 它也有很多具有许多用例的示例

Since it doesn’t use any native linking, installation and implementation was pretty simple and straightforward.

由于它不使用任何本地链接,因此安装和实现非常简单明了。

If you just want to see the source code of the example project, find the project repo here.

如果您只想查看示例项目的源代码,请在此处找到项目库。

Now that’s done, let’s get this party rolling.

现在完成了,让我们开始这个聚会。

入门 (Getting Started)

Create a React native project and install all the required dependencies.

创建一个React本机项目并安装所有必需的依赖项。

~ react-native init ReactNativeTooltip

We’ll also need to install and link the react-native-svg library.

我们还需要安装并链接react-native-svg库。

~ npm i react-native-svg
~ react-native link react-native-svg

If you face any problem linking the library automatically using the link command, follow the manual steps mentioned in the official documentation.

如果您在使用链接命令自动链接库时遇到任何问题,请按照官方文档中提到的手动步骤进行操作

Now, finally install the react-native-svg-charts .

现在,最后安装react-native-svg-charts

~ npm install react-native-svg-charts

获取虚拟数据 (Getting the Dummy data)

Before we dive any further we’ll need to have some data that we can use for rendering our AreaChart. We’ll be using a third-party service called Mockaroo to generate some mock data for our area chart.

在进一步深入之前,我们需要具有一些可用于渲染AreaChart 。 我们将使用名为Mockaroo的第三方服务为面积图生成一些模拟数据。

Ideally, we’ll be getting this data from an API that we’ll store it in the component state and then feed to our area component.

理想情况下,我们将从API中获取此数据,然后将其存储在组件状态中,然后馈入我们的Area组件。

Here is how my dummy JSON data looks. See here for the full JSON data file.

这是我的虚拟JSON数据的外观。 有关完整的JSON数据文件,请参见此处

export const DATA = [  {    id: 1,    date: ‘2019–01–26T22:37:01Z’,    score: 3,  },  {    id: 2,    date: ‘2019–01–06T06:03:09Z’,    score: 9,  },  {    id: 3,    date: ‘2019–01–28T14:10:00Z’,    score: 10,  },  {    id: 4,    date: ‘2019–01–03T02:07:38Z’,    score: 7,  },  ...]

使用React Native SVG图表 (Using React Native SVG charts)

react-native-svg-charts has lots of components that we can use to create graphs. In this tutorial, we’ll use AreaChart component but you can use any one of the available charts components. Here is how an Areachart chart component looks:

react-native-svg-charts具有许多可用于创建图形的组件。 在本教程中,我们将使用AreaChart组件,但您可以使用任何可用的图表组件。 这是Areachart图表组件的外观:

<AreaChart  style={{ height: '70%' }}  data={data}  yAccessor={({ item }) => item.score}  xAccessor={({ item }) => moment(item.date)}  contentInset={contentInset}  svg={{ fill: '#003F5A' }}  numberOfTicks={10}  yMin={0}  yMax={10}>

Let’s go through the important props that we are using in the AreaChart.

让我们浏览一下AreaChart中使用的重要道具。

  • data : This is a required field and must be an array.

    data :这是必填字段,必须是一个数组。

  • yAccessor: A function that takes each entry of data (named "item") as well as the index and returns the y-value of that entry.

    yAccessor :该函数获取data每个条目(名为“ item”)以及索引,并返回该条目的y值。

  • xAccessor: Same as yAccessor but returns the x-value of that entry.

    xAccessor:xAccessor:相同,但返回yAccessor目的x值。

You can read more about the other available props in the official documentation.

您可以在官方文档中了解有关其他可用道具的更多信息。

添加装饰器 (Adding Decorators)

React native SVG charts was built to be as extensible as possible. All charts can be extended with “decorators”, a component that somehow styles or enhances your chart. Simply pass in a react-native-svg compliant component as a child to the graph and it will be called with all the necessary information to layout your decorator.

React本机SVG图表被构建为尽可能可扩展。 所有图表都可以使用“装饰器”扩展,该组件以某种方式设计或增强了图表的样式。 只需将一个react-native-svg兼容组件作为子代传递到该图,它将使用所有必需的信息进行调用,以布局装饰器。

For this tutorial, we’ll need two decorators, one for the datapoint marker and another one for the tooltip.

在本教程中,我们将需要两个装饰器,一个用于数据点标记,另一个用于工具提示。

Make sure you place Decorators inside the AreaChart component. Otherwise they won’t render.

确保将装饰器放置在AreaChart组件内。 否则,它们将不会渲染。

添加标记数据点 (Adding Marker Data Points)

Let’s create a decorator to be used as a marker at each data point in the chart.

让我们创建一个装饰器以用作图表中每个数据点的标记。

const ChartPoints = ({ x, y, color }) =>  data.map((item, index) => (   <Circle     key={index}     cx={x(moment(item.date))}     cy={y(item.score)}     r={6}     stroke={color}     fill=”white”     onPress={() =>       this.setState({         tooltipX: moment(item.date),         tooltipY: item.score,         tooltipIndex: index,       })     }  />));

We need a circular marker for each item in the data array. And, for that, we are going to loop through each item in the data array and return Circle SVG component for each one of them.

对于数据数组中的每个项目,我们都需要一个圆形标记。 而且,为此,我们将遍历数据数组中的每个项目,并为每个项目返回Circle SVG组件。

Now, to position them on the chart, we’ll use the cx and cy props to position them horizontally and vertically, respectively. For cx we will use date key and for cy we will use the score key.

现在,要将它们放置在图表上,我们将使用cxcy道具分别将它们水平和垂直放置。 对于cx我们将使用date键,对于cy我们将使用score键。

Apart from that, we’ll also pass onPress prop that will set three states, tooltipX, tooltipY and tooltipIndex when any of the data points are pressed. We’ll use then use these states to position the Tooltip decorator.

除此之外,我们还将传递onPress tooltipXtooltipY tooltipIndex在按下任何数据点时设置三个状态,即tooltipXtooltipYtooltipIndex 。 然后,我们将使用这些状态来定位Tooltip装饰器。

添加工具提示 (Adding Tooltip)

Now that we have necessary information like x-axis(tooltipX), the y-axis (tooltipY)and index(tooltipIndex) of the marker pressed, we can use them to place Tooltip on the AreaChart.

现在我们有了必要的信息,例如所按下标记的x轴(tooltipX),y轴(tooltipY)和索引(tooltipIndex),我们可以使用它们将Tooltip放置在AreaChart

We’ll create a new file for the Tooltip Decorator.

我们将为Tooltip装饰器创建一个新文件

const Tooltip = ({ x, y, tooltipX, tooltipY, color, index, dataLength,}) => {
let xAxis = 4;  if (dataLength > 4) {    if (index < 2) {      xAxis = 35;    } else if (index > dataLength — 2) {      xAxis = -20;    } else {     xAxis = 4;    }  }
return (    <;G x={x(tooltipX) — 40} y={y(tooltipY)}>      <G y={tooltipY > 9 ? 20 : -29} x={xAxis}>        <Rect x={-2} y={0} height={22} width={70} stroke={color} fill=”white” ry={10} rx={10} />        <Rect x={-2} y={0} height={22} width={18} fill={color} ry={10} rx={10} />        <Rect x={10} y={0} height={22} width={tooltipY > 9 ? 12 : 10} fill={color} /&gt;        <Text x={6} y={14} stroke=”#fff”>          {tooltipY}        </Text>        <Text x={tooltipY > 9 ? 24 : 22} y={14}>          {moment(tooltipX).format(‘MMM DD’)}        </Text>      </G>    </G>  );};

Don’t get confused or intimidated by all the React, G and Text tags here, most of them are just for the styling of the tooltip.

不要在这里被所有的ReactGText标签所迷惑或恐吓,它们中的大多数只是用于工具提示的样式。

Just focus on tooltipX and, tooltipY that we are using to position the Tooltip horizontally and vertically on the chart. These values are the same as cx and cy that we used for the marker, except that we are adding and subtracting some values to adjust them on the chart.

只需关注tooltipX和我们用来在图表上水平和垂直放置Tooltip tooltipY 。 这些值与用于标记的cxcy相同,除了我们要添加和减去一些值以在图表上进行调整。

Apart from that, we are using tooltipIndex to offset the first and last Tooltip so that they don’t get cut off on the sides.

除此之外,我们使用tooltipIndex来偏移第一个和最后一个Tooltip,以使它们不会在侧面被切除。

Here is the full source code of a working example.

是一个工作示例的完整源代码。

最后的想法 (Final Thoughts)

That is all we need to do to create charts, markers, and tooltips. This is just a basic implementation of what can be achieved using the react-native-svg-charts library.

这就是我们创建图表,标记和工具提示所需要做的全部工作。 这只是使用react-native-svg-charts库可以实现的功能的基本实现。

If you want to explore more, do check out their examples repo where they showcase tons of other use cases.

如果您想探索更多内容,请查看他们的示例存储库,其中展示了大量其他用例。

For the sake of brevity I’ve skipped some boilerplate code which you can find on the Github repo.
为了简洁起见,我跳过了一些可在Github存储库中找到的样板代码。

Let me know if you find anything confusing. If you have worked on react native charts, do share what libraries and use cases you came across.

如果您发现任何令人困惑的地方,请告诉我。 如果您曾处理过本机图表,请共享您遇到的库和用例。

翻译自: https://www.freecodecamp.org/news/how-to-build-react-native-charts-with-dynamic-tooltips-64aefc550c95/

 类似资料: