如何使用动态工具提示构建React Native图表
by Vikrant Negi
通過(guò)Vikrant Negi
如何使用動(dòng)態(tài)工具提示構(gòu)建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.
無(wú)論是在Web上還是在移動(dòng)應(yīng)用程序上創(chuàng)建圖表,一直都是一項(xiàng)有趣且具有挑戰(zhàn)性的任務(wù),尤其是在React Native中。 很難找到可以同時(shí)滿足您的功能和設(shè)計(jì)需求的合適的庫(kù)。 您可以嘗試制作自己的圖表,但這通常伴隨著從頭開(kāi)始學(xué)習(xí)和實(shí)現(xiàn)事物的開(kāi)銷。
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.
如果您像我一樣是初學(xué)者,則可能要使用現(xiàn)有的圖表庫(kù)。 考慮到React Native社區(qū)還很年輕,您幾乎沒(méi)有可用的實(shí)現(xiàn)和自定義圖表的選項(xiàng)。
問(wèn)題陳述 (Problem Statement)
Before starting our journey deep into the woods, I would like to introduce you to our problem statement.
在開(kāi)始深入森林之前,我想向您介紹我們的問(wèn)題陳述。
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.
在本教程中,我們將繪制一個(gè)面積圖,并在每個(gè)數(shù)據(jù)點(diǎn)處添加一個(gè)圓形標(biāo)記,可以進(jìn)一步點(diǎn)擊以顯示包含x和y坐標(biāo)值的工具提示。
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.
為了解決這個(gè)問(wèn)題,我對(duì)一些現(xiàn)有的React Native庫(kù)進(jìn)行了一些研究,并將其范圍縮小到兩個(gè), react-native-charts-wrapper和react-native-svg-charts 。
React本機(jī)圖表包裝 (React Native Charts Wrapper)
Our first contender, react-native-charts-wrapper is a React Native wrapper of popular Native charting library MPAndroidChart and Charts.
我們的第一個(gè)競(jìng)爭(zhēng)者react-native-charts-wrapper是流行的本機(jī)圖表庫(kù)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.
該庫(kù)是高度可配置的,并且由于它使用本機(jī)圖表庫(kù),因此可提供柔滑的平滑過(guò)渡和觸摸支持。 它在Github倉(cāng)庫(kù)上也有大量的用例示例。
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.
剛開(kāi)始,考慮到它的性能和定制性,這是我的首選。 它有一個(gè)非常長(zhǎng)且特定的安裝指南,隨后我能夠在iOS和Android設(shè)備上安裝并運(yùn)行它。
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上都能正常運(yùn)行。 但是,當(dāng)我嘗試創(chuàng)建iOS版本時(shí),它給了我一個(gè)錯(cuò)誤。 經(jīng)過(guò)數(shù)小時(shí)的搜索GitHub問(wèn)題和Google的搜索后,我決定反對(duì)它。
React本機(jī)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這是我能找到的下一個(gè)最佳解決方案。
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來(lái)繪制圖表。 它也有很多具有許多用例的示例 。
Since it doesn’t use any native linking, installation and implementation was pretty simple and straightforward.
由于它不使用任何本地鏈接,因此安裝和實(shí)現(xiàn)非常簡(jiǎn)單明了。
If you just want to see the source code of the example project, find the project repo here.
如果您只想查看示例項(xiàng)目的源代碼,請(qǐng)?jiān)诖颂幷业巾?xiàng)目庫(kù)。
Now that’s done, let’s get this party rolling.
現(xiàn)在完成了,讓我們開(kāi)始這個(gè)聚會(huì)。
入門 (Getting Started)
Create a React native project and install all the required dependencies.
創(chuàng)建一個(gè)React本機(jī)項(xiàng)目并安裝所有必需的依賴項(xiàng)。
~ react-native init ReactNativeTooltipWe’ll also need to install and link the react-native-svg library.
我們還需要安裝并鏈接react-native-svg庫(kù)。
~ npm i react-native-svg~ react-native link react-native-svgIf you face any problem linking the library automatically using the link command, follow the manual steps mentioned in the official documentation.
如果您在使用鏈接命令自動(dòng)鏈接庫(kù)時(shí)遇到任何問(wèn)題,請(qǐng)按照官方文檔中提到的手動(dòng)步驟進(jìn)行操作 。
Now, finally install the react-native-svg-charts .
現(xiàn)在,最后安裝react-native-svg-charts 。
~ npm install react-native-svg-charts獲取虛擬數(shù)據(jù) (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.
在進(jìn)一步深入之前,我們需要具有一些可用于渲染AreaChart 。 我們將使用名為Mockaroo的第三方服務(wù)為面積圖生成一些模擬數(shù)據(jù)。
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中獲取此數(shù)據(jù),然后將其存儲(chǔ)在組件狀態(tài)中,然后饋入我們的Area組件。
Here is how my dummy JSON data looks. See here for the full JSON data file.
這是我的虛擬JSON數(shù)據(jù)的外觀。 有關(guān)完整的JSON數(shù)據(jù)文件,請(qǐng)參見(jiàn)此處 。
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具有許多可用于創(chuàng)建圖形的組件。 在本教程中,我們將使用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.
讓我們?yōu)g覽一下AreaChart中使用的重要道具。
data : This is a required field and must be an array.
data :這是必填字段,必須是一個(gè)數(shù)組。
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 :該函數(shù)獲取data每個(gè)條目(名為“ 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.
您可以在官方文檔中了解有關(guān)其他可用道具的更多信息。
添加裝飾器 (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本機(jī)SVG圖表被構(gòu)建為盡可能可擴(kuò)展。 所有圖表都可以使用“裝飾器”擴(kuò)展,該組件以某種方式設(shè)計(jì)或增強(qiáng)了圖表的樣式。 只需將一個(gè)react-native-svg兼容組件作為子代傳遞到該圖,它將使用所有必需的信息進(jìn)行調(diào)用,以布局裝飾器。
For this tutorial, we’ll need two decorators, one for the datapoint marker and another one for the tooltip.
在本教程中,我們將需要兩個(gè)裝飾器,一個(gè)用于數(shù)據(jù)點(diǎn)標(biāo)記,另一個(gè)用于工具提示。
Make sure you place Decorators inside the AreaChart component. Otherwise they won’t render.
確保將裝飾器放置在AreaChart組件內(nèi)。 否則,它們將不會(huì)渲染。
添加標(biāo)記數(shù)據(jù)點(diǎn) (Adding Marker Data Points)
Let’s create a decorator to be used as a marker at each data point in the chart.
讓我們創(chuàng)建一個(gè)裝飾器以用作圖表中每個(gè)數(shù)據(jù)點(diǎn)的標(biāo)記。
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.
對(duì)于數(shù)據(jù)數(shù)組中的每個(gè)項(xiàng)目,我們都需要一個(gè)圓形標(biāo)記。 而且,為此,我們將遍歷數(shù)據(jù)數(shù)組中的每個(gè)項(xiàng)目,并為每個(gè)項(xiàng)目返回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.
現(xiàn)在,要將它們放置在圖表上,我們將使用cx和cy道具分別將它們水平和垂直放置。 對(duì)于cx我們將使用date鍵,對(duì)于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 tooltipX , tooltipY tooltipIndex在按下任何數(shù)據(jù)點(diǎn)時(shí)設(shè)置三個(gè)狀態(tài),即tooltipX , tooltipY和tooltipIndex 。 然后,我們將使用這些狀態(tài)來(lái)定位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.
現(xiàn)在我們有了必要的信息,例如所按下標(biāo)記的x軸(tooltipX),y軸(tooltipY)和索引(tooltipIndex),我們可以使用它們將Tooltip放置在AreaChart 。
We’ll create a new file for the Tooltip Decorator.
我們將為Tooltip裝飾器創(chuàng)建一個(gè)新文件 。
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} /> <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.
不要在這里被所有的React , G和Text標(biāo)簽所迷惑或恐嚇,它們中的大多數(shù)只是用于工具提示的樣式。
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.
只需關(guān)注tooltipX和我們用來(lái)在圖表上水平和垂直放置Tooltip tooltipY 。 這些值與用于標(biāo)記的cx和cy相同,除了我們要添加和減去一些值以在圖表上進(jìn)行調(diào)整。
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來(lái)偏移第一個(gè)和最后一個(gè)Tooltip,以使它們不會(huì)在側(cè)面被切除。
Here is the full source code of a working example.
這是一個(gè)工作示例的完整源代碼。
最后的想法 (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.
這就是我們創(chuàng)建圖表,標(biāo)記和工具提示所需要做的全部工作。 這只是使用react-native-svg-charts庫(kù)可以實(shí)現(xiàn)的功能的基本實(shí)現(xiàn)。
If you want to explore more, do check out their examples repo where they showcase tons of other use cases.
如果您想探索更多內(nèi)容,請(qǐng)查看他們的示例存儲(chǔ)庫(kù),其中展示了大量其他用例。
For the sake of brevity I’ve skipped some boilerplate code which you can find on the Github repo.為了簡(jiǎn)潔起見(jiàn),我跳過(guò)了一些可在Github存儲(chǔ)庫(kù)中找到的樣板代碼。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.
如果您發(fā)現(xiàn)任何令人困惑的地方,請(qǐng)告訴我。 如果您曾處理過(guò)本機(jī)圖表,請(qǐng)共享您遇到的庫(kù)和用例。
翻譯自: https://www.freecodecamp.org/news/how-to-build-react-native-charts-with-dynamic-tooltips-64aefc550c95/
總結(jié)
以上是生活随笔為你收集整理的如何使用动态工具提示构建React Native图表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: vue生成静态js文件_如何立即使用Vu
- 下一篇: 梦到打针是什么意思周公解梦