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

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-wrapper和react-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是流行的本机图表库MPAndroidChart和Charts的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/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392548.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何解决ajax跨域问题(转)

由 于此前很少写前端的代码(哈哈&#xff0c;不合格的程序员啊)&#xff0c;最近项目中用到json作为系统间交互的手段&#xff0c;自然就伴随着众多ajax请求&#xff0c;随之而来的就是要解决 ajax的跨域问题。本篇将讲述一个小白从遇到跨域不知道是跨域问题&#xff0c;到知道…

mysql并发错误_又谈php+mysql并发数据出错问题

最近&#xff0c;项目中的所有crond定时尽量取消&#xff0c;改成触发式。比如每日6点清理数据。原来的逻辑&#xff0c;写一个crond定时搞定现在改为触发式6点之后第一个玩家/用户 进入&#xff0c;才开始清理数据。出现了一个问题1 如何确保第一个玩家触发&#xff1f;updat…

leetcode 621. 任务调度器(贪心算法)

给你一个用字符数组 tasks 表示的 CPU 需要执行的任务列表。其中每个字母表示一种不同种类的任务。任务可以以任意顺序执行&#xff0c;并且每个任务都可以在 1 个单位时间内执行完。在任何一个单位时间&#xff0c;CPU 可以完成一个任务&#xff0c;或者处于待命状态。 然而&…

英国脑科学领域_来自英国A级算法崩溃的数据科学家的4课

英国脑科学领域In the UK, families, educators, and government officials are in an uproar about the effects of a new algorithm for scoring “A-levels,” the advanced level qualifications used to evaluate students’ knowledge of specific subjects in preparati…

MVC发布后项目存在于根目录中的子目录中时的css与js、图片路径问题

加载固定资源js与css <script src"Url.Content("~/Scripts/js/jquery.min.js")" type"text/javascript"></script> <link href"Url.Content("~/Content/css/shop.css")" rel"stylesheet" type&quo…

telegram 机器人_学习使用Python在Telegram中构建您的第一个机器人

telegram 机器人Imagine this, there is a message bot that will send you a random cute dog image whenever you want, sounds cool right? Let’s make one!想象一下&#xff0c;有一个消息机器人可以随时随地向您发送随机的可爱狗图像&#xff0c;听起来很酷吧&#xff1…

判断输入的字符串是否为回文_刷题之路(九)--判断数字是否回文

Palindrome Number问题简介&#xff1a;判断输入数字是否是回文,不是返回0,负数返回0举例:1:输入: 121输出: true2:输入: -121输出: false解释: 回文为121-&#xff0c;所以负数都不符合3:输入: 10输出: false解释: 倒序为01&#xff0c;不符合要求解法一&#xff1a;这道题比较…

python + selenium 搭建环境步骤

介绍在windows下&#xff0c;selenium python的安装以及配置。1、首先要下载必要的安装工具。 下载python&#xff0c;我安装的python3.0版本,根据你自己的需要安装下载setuptools下载pip(python的安装包管理工具) 配置系统的环境变量 python,需要配置2个环境变量C:\Users\AppD…

VirtualBox 虚拟机复制

本文简单讲两种情况下的复制方式 1 跨电脑复制 2 同一virtrul box下 虚拟机复制 ---------------------------------------------- 1 跨电脑复制 a虚拟机 是老的虚拟机 b虚拟机 是新的虚拟机 新虚拟机b 新建&#xff0c; 点击下一步会生成 相应的文件夹 找到老虚拟机a的 vdi 文…

javascript实用库_编写实用JavaScript的实用指南

javascript实用库by Nadeesha Cabral通过Nadeesha Cabral 编写实用JavaScript的实用指南 (A practical guide to writing more functional JavaScript) Functional programming is great. With the introduction of React, more and more JavaScript front-end code is being …

数据库数据过长避免_为什么要避免使用商业数据科学平台

数据库数据过长避免让我们从一个类比开始 (Lets start with an analogy) Stick with me, I promise it’s relevant.坚持下去&#xff0c;我保证这很重要。 If your selling vegetables in a grocery store your business value lies in your loyal customers and your positi…

mysql case快捷方法_MySQL case when使用方法实例解析

首先我们创建数据库表&#xff1a; CREATE TABLE t_demo (id int(32) NOT NULL,name varchar(255) DEFAULT NULL,age int(2) DEFAULT NULL,num int(3) DEFAULT NULL,PRIMARY KEY (id)) ENGINEInnoDB DEFAULT CHARSETutf8;插入数据&#xff1a;INSERT INTO t_demo VALUES (1, 张…

【~~~】POJ-1006

很简单的一道题目&#xff0c;但是引出了很多知识点。 这是一道中国剩余问题&#xff0c;先贴一下1006的代码。 #include "stdio.h" #define MAX 21252 int main() { int p , e , i , d , n 1 , days 0; while(1) { scanf("%d %d %d %d",&p,&e,&…

Java快速扫盲指南

文章转自&#xff1a;https://segmentfault.com/a/1190000004817465#articleHeader22 JDK&#xff0c;JRE和 JVM 的区别 JVM&#xff1a;java 虚拟机&#xff0c;负责将编译产生的字节码转换为特定机器代码&#xff0c;实现一次编译多处执行&#xff1b; JRE&#xff1a;java运…

xcode扩展_如何将Xcode插件转换为Xcode扩展名

xcode扩展by Khoa Pham通过Khoa Pham 如何将Xcode插件转换为Xcode扩展名 (How to convert your Xcode plugins to Xcode extensions) Xcode is an indispensable IDE for iOS and macOS developers. From the early days, the ability to build and install custom plugins ha…

leetcode 861. 翻转矩阵后的得分(贪心算法)

有一个二维矩阵 A 其中每个元素的值为 0 或 1 。 移动是指选择任一行或列&#xff0c;并转换该行或列中的每一个值&#xff1a;将所有 0 都更改为 1&#xff0c;将所有 1 都更改为 0。 在做出任意次数的移动后&#xff0c;将该矩阵的每一行都按照二进制数来解释&#xff0c;矩…

数据分析团队的价值_您的数据科学团队的价值

数据分析团队的价值This is the first article in a 2-part series!!这是分两部分的系列文章中的第一篇&#xff01; 组织数据科学 (Organisational Data Science) Few would argue against the importance of data in today’s highly competitive corporate world. The tech…

mysql 保留5位小数_小猿圈分享-MySQL保留几位小数的4种方法

今天小猿圈给大家分享的是MySQL使用中4种保留小数的方法&#xff0c;希望可以帮助到大家&#xff0c;让大家的工作更加方便。1 round(x,d)用于数据x的四舍五入, round(x) ,其实就是round(x,0),也就是默认d为0&#xff1b;这里有个值得注意的地方是&#xff0c;d可以是负数&…

leetcode 842. 将数组拆分成斐波那契序列(回溯算法)

给定一个数字字符串 S&#xff0c;比如 S “123456579”&#xff0c;我们可以将它分成斐波那契式的序列 [123, 456, 579]。 形式上&#xff0c;斐波那契式序列是一个非负整数列表 F&#xff0c;且满足&#xff1a; 0 < F[i] < 2^31 - 1&#xff0c;&#xff08;也就是…

博主简介

面向各层次&#xff08;从中学到博士&#xff09;提供GIS和Python GIS案例实验实习培训&#xff0c;以解决问题为导向&#xff0c;以项目实战为主线&#xff0c;以科学研究为思维&#xff0c;不讲概念&#xff0c;不局限理论&#xff0c;简单照做&#xff0c;即学即会。 研究背…