如何使用動態工具提示構建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.pswp.cn/news/392548.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392548.shtml
英文地址,請注明出處:http://en.pswp.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;即學即會。 研究背…