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 ofdata
(named "item") as well as the index and returns the y-value of that entry.yAccessor
:該函數獲取data
每個條目(名為“ item”)以及索引,并返回該條目的y值。xAccessor:
Same asyAccessor
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.
現在,要將它們放置在圖表上,我們將使用cx
和cy
道具分別將它們水平和垂直放置。 對于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
tooltipX
, tooltipY
tooltipIndex
在按下任何數據點時設置三個狀態,即tooltipX
, tooltipY
和tooltipIndex
。 然后,我們將使用這些狀態來定位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} /> <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
標簽所迷惑或恐嚇,它們中的大多數只是用于工具提示的樣式。
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
。 這些值與用于標記的cx
和cy
相同,除了我們要添加和減去一些值以在圖表上進行調整。
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/