React Native works a lot like React, implementing JSX, state, and props. Of course, React Native is built on Native components, instead of HTML elements. Therefore, if you are familiar with normal React, it will be easy to pick up React Native, as long as you can understand the different components used. In this guide, we will look through the basic Native components that React Native uses.
React Native的工作方式与React类似,实现JSX ,state和props。 当然,React Native是基于Native组件而不是HTML元素构建的。 因此,如果您熟悉普通的React,只要您能够理解所使用的不同组件,就会很容易获得React Native。 在本指南中,我们将浏览React Native使用的基本Native组件。
Unlike React for the web, React Native requires you to import each component in your project - after all, each component is setup to work both in Android and iOS. This is the reason we use React Native, not to mention being able to write everything in JavaScript. To import each component, we will simply add it to our imported object:
与Web上的React不同,React Native要求您导入项目中的每个组件-毕竟,每个组件都设置为可在Android和iOS上运行。 这就是我们使用React Native的原因,更不用说能够用JavaScript编写所有内容了。 要导入每个组件,我们只需将其添加到我们的导入对象中:
import { Text, View } from "react-native";
Text
and View
are the two most basic building blocks of any React Native application. They are the best place for anyone to start when learning React Native.
Text
和View
是任何React Native应用程序的两个最基本的构建基块。 它们是任何人学习React Native的最佳起点。
文字和检视 (Text and View)
As you can guess, <Text></Text>
is a wrapper for any text in your page. This component is similar to a <p>
tag in HTML. Now, similar to a <div></div>
tag, you would wrap your <Text></Text>
in a <View></View>
. That’s right, <View>
acts very similar to <div>
, and the basic idea is that it is a container perfect for dividing up and styling your page.
如您所料, <Text></Text>
是页面中任何文本的包装。 该组件类似于HTML中的<p>
标记。 现在,类似于<div></div>
标记,您可以将<Text></Text>
包裹在<View></View>
。 没错, <View>
行为与<div>
非常相似,其基本思想是,它是用于分隔和样式化页面的完美容器。
Here is the basic set up of a React Native page:
这是React Native页面的基本设置:
import React from "react";
import { View, Text } from "react-native";
export default class App extends React.Component {
render() {
return (
<View>
<Text> Hello World! </Text>
</View>
);
}
}
Both <Text>
and <View>
components have style props where you can set colors, sizes, etc. However, there are some important distinctions to keep in mind. Although View
does work similarly to a div
element, you can’t wrap any text in it, like this <View>this text doesn't work</View>
(not that you should with a div
element anyway). That would cause an exception and that is why we use the <Text>
component.
<Text>
和<View>
组件都有样式道具,您可以在其中设置颜色,大小等。但是,要记住一些重要的区别。 尽管View
工作原理与div
元素类似,但是您不能在其中包装任何文本,例如<View>this text doesn't work</View>
(不是您应该div
使用div
元素)。 这将导致异常,这就是为什么我们使用<Text>
组件。
Speaking of the <Text>
component, you can wrap another component inside it like this:
说到<Text>
组件,您可以像这样包装另一个组件:
<Text style={{ color: red }}>
<Text style={{ fontSize: 24 }}>Here is the first text </Text>
<Text style={{ fontSize: 14 }}>And the second text.</Text>
</Text>
// comes out as 'Here is the first text And the second text'
When <Text>
is wrapping <Text>
, the nested text will come out on the same line, assuming there is enough space. However, if the two <Text>
components were wrapped in a <View>
, they would appear on separate lines.
当<Text>
换行<Text>
,假设有足够的空间,嵌套的文本将显示在同一行上。 但是,如果将两个<Text>
组件包装在<View>
,则它们将出现在单独的行上。
文字输入 (TextInput)
This component is somewhat like an <input>
HTML element, but as its name would indicate, it’s only for a text input. Instead of using onChange
callback, you can use onChangeText
to detect changes to the text in the <TextInput>
component. You can use onChange
, but it returns an object: { nativeEvent: { eventCount, target, text} }
.
该组件有点像<input>
HTML元素,但正如其名称所示,它仅用于文本输入。 可以使用onChangeText
来检测<TextInput>
组件中文本的更改,而不是使用onChange
回调。 您可以使用onChange
,但它返回一个对象: { nativeEvent: { eventCount, target, text} }
。
Other than that, there are plenty of cool features on this component. You can set which keyboard pulls up on the phone with keyboardType
(such as keyboardType='email-address'
), toggle the auto-correct feature, set the textContentType
for the phone to autofill the text (like your password on your keychain), and so much more.
除此之外,此组件还有很多很酷的功能。 您可以使用keyboardType
(例如keyboardType='email-address'
)设置在手机上拉起哪个键盘,切换自动更正功能,为手机设置textContentType
以自动填充文本(例如您在钥匙串上的密码),还有更多。
按钮和警报 (Button And Alert)
The <Button />
component is the first component I noticed that had major differences from its sibling (the HTML <button>
element). The React Native <Button />
has an onPress()
prop, as opposed to anything click-related. It also has a title
prop for the text which goes inside it. Finally, it doesn’t have a style prop, but only a color prop.
<Button />
组件是我注意到的第一个与同级(HTML <button>
元素)有很大不同的组件。 React Native <Button />
具有onPress()
道具,与任何与点击相关的东西都没有。 它还具有用于其中的文本的title
道具。 最后,它没有样式道具,只有一个颜色道具。
That last point is a pretty big difference. Now you can (and would) wrap it in a View and style it with that wrapper. That is a common way to deal with some limitations on React Native components and you will likely find yourself using View to wrap other components all the time. What I find myself using more often is a component we will cover a little later - <TouchableOpacity >
.
最后一点是一个很大的不同。 现在,您可以(并且会)将其包装在View中并使用该包装器设置样式。 这是解决React Native组件上某些限制的一种常用方法,您可能会发现自己一直在使用View包装其他组件。 我发现自己经常使用的是稍后将介绍的组件- <TouchableOpacity >
。
What I also found interesting about this basic Button
component is that on the iOS platform, it only shows up as the text in the title - with no background. Therefore, the color prop will only change the text color, though on Android it will change the background color of the button.
对于该基本的Button
组件,我还发现有趣的是,在iOS平台上,它仅显示为标题中的文本-没有背景。 因此,颜色道具只会更改文本颜色,尽管在Android上它将更改按钮的背景颜色。
Here is a quick example of a Button component.
这是一个Button组件的简单示例。
<Button
onPress={() => Alert.alert("button pressed!")}
title="alert button"
color="blue"
/>
Note: we are using Alert
which is also imported from the React Native core. This will show an alert on top of our screen, similar to a web alert()
.
注意:我们使用的Alert
也从React Native核心导入。 这将在屏幕上方显示一个警报,类似于Web alert()
。
图片和图片背景 (Image and ImageBackground)
The <Image />
component is pretty similar to a HTML img
tag. However, there are a few differences, such as changing the src
prop to source
. Also, the source itself operates differently: for local images, you import them with require
, like this <Image source={require('path/to/local/image)} />
.
<Image />
组件非常类似于HTML img
标签。 但是,有一些差异,例如将src
prop更改为source
。 同样,源本身的操作也不同:对于本地图像,可以使用require
导入它们,例如<Image source={require('path/to/local/image)} />
。
Also, in the source prop, you can use the URI like this: <Image source={{uri: 'https://imagesite.com/path/to/image'}} style={{height: 100, width: 100, resizeMode: contain}}
. Notice the uri is an object, so it needs another set of curly braces, just like inline styles. There are plenty of other props to check out here, but a common one to use is resizeMode
. This determines how to resize your image and to fit your image within a parent View
component.
另外,在源道具中,您可以像这样使用URI: <Image source={{uri: 'https://imagesite.com/path/to/image'}} style={{height: 100, width: 100, resizeMode: contain}}
。 注意uri是一个对象,因此它需要另一组花括号,就像内联样式一样。 还有很多其他道具可以在这里签出,但是一个常用的道具是resizeMode
。 这确定了如何调整图像的大小以及如何在父View
组件中适合图像。
The ImageBackground
component is similar to the <Image />
component as it receives the same props, but the main distinction here, is that it can have child elements. The <Image />
component is self-closing. The thing about ImageBackground
is, is that it’s pretty basic and a better solution to setting a background image might be to either build your own component or simply set an Image
as absolute with lower opacity and behind everything.
ImageBackground
组件与<Image />
组件相似,因为它接收相同的道具,但是这里的主要区别是它可以具有子元素。 <Image />
组件是自动关闭的。 关于ImageBackground
的事情是,它非常基本,并且设置背景图像的更好解决方案可能是构建自己的组件,或者只是将Image
设置为具有较低不透明度且位于所有物体后面的绝对Image
。
可触摸的 (The Touchables)
One thing you’ll notice in React Native is that many of the components we have covered do not have all the props you would normally implement in a web app. The <Image />
component does not have an onPress
prop and the <Button />
component doesn’t have a style
prop. Any Touchable component can really help here.
在React Native中您会注意到的一件事是,我们介绍的许多组件都没有通常在Web应用程序中实现的所有道具。 <Image />
组件没有onPress
属性,而<Button />
组件没有style
属性。 任何Touchable组件都可以在这里真正提供帮助。
For instance, you can wrap any image component in a Touchable:
例如,您可以将任何图像组件包装在Touchable中:
<TouchableHighlight onPress={this.pressHandle}>
<Image />
</TouchableHighlight>
The TouchableHighlight
in the above example acts like a container for the image with a function when pressed, including a built-in animation. You could also just add View
and Text
components within a Touchable component to act just like a <Button />
, but with customizable style.
上面示例中的TouchableHighlight
就像是图像的容器,按下后具有功能,包括内置动画。 您还可以在Touchable组件内添加View
和Text
组件,使其像<Button />
,但具有可自定义的样式。
Now there are a few different Touchable components such as:
现在有一些不同的Touchable组件,例如:
- TouchableHighlight: when pressed, darkens the background. TouchableHighlight:按下时,背景变暗。
- TouchableOpacity: when pressed, dims the opacity of the button. TouchableOpacity:按下时,使按钮的不透明度变暗。
- TouchableNativeFeedback: Android-only ripple effect. TouchableNativeFeedback:仅限Android的涟漪效果。
- TouchableWithoutFeedback: a press without any feedback/effect. TouchableWithoutFeedback:没有任何反馈/效果的印刷机。
These animations happen when pressed. The Touchable components also have their own unique props which you can customize to your own liking.
这些动画在按下时发生。 Touchable组件还具有自己独特的道具,您可以根据自己的喜好自定义它们。
ScrollView,SafeAreaView和FlatList (ScrollView, SafeAreaView and FlatList)
So far we’ve looked at all the basic building blocks of a React Native app. However, there are plenty more, and one thing you will quickly find is that a phone screen won’t automatically scroll if the content height or width exceeds the screen size. This may surprise you, when you have everything wrapped in a View
component, the overflow will be hidden.
到目前为止,我们已经研究了React Native应用程序的所有基本构建块。 但是,还有更多内容,您会很快发现,如果内容的高度或宽度超过屏幕尺寸,电话屏幕将不会自动滚动。 这可能会让您感到惊讶,当您将所有内容包装在View
组件中时,溢出将被隐藏。
That’s where the simple implementation of ScrollView
comes in. The ScrollView
component is the basic component to enable scrolling. However, FlatList
also enables scrolling, but it has a much greater capacity than ScrollView
.
这就是ScrollView
的简单实现的地方ScrollView
组件是启用滚动的基本组件。 但是, FlatList
也支持滚动,但是它的容量比ScrollView
大得多。
Now, the basic setup of ScrollView
is giving boundaries to the scrollable-view, which would most likely be the screen height and width. Like an image, you can wrap ScrollView
to give it these boundaries. Normally, you can use a normal View
component for this, but if you have an iPhone X, you may find that your View
goes up behind the rounded corners or sensor cluster. The SafeAreaView
will take care of this, giving adequate padding so the entire screen will be visible. Either way, to stretch the entire screen, you can simply set the style of the parent view to flex: 1
.
现在, ScrollView
的基本设置为可滚动视图提供了边界,最有可能是屏幕的高度和宽度。 就像图像一样,您可以包装ScrollView
为其赋予这些边界。 通常,您可以为此使用常规的View
组件,但是如果您拥有iPhone X,则可能会发现View
出现在圆角或传感器群集后面。 SafeAreaView
会注意这一点,并提供足够的填充,以便整个屏幕都可见。 无论哪种方式,要拉伸整个屏幕,只需将父视图的样式设置为flex: 1
。
This setup with ScrollView
will work when the height of all your elements is determined locally - as in, the height of your page will always be set the same. If there is data coming in that affects the dimensions of the content, it may be difficult to determine the dimensions of the ScrollView
. There are ways to compensate for that, but an even bigger limitation to ScrollView
is that it will render everything all at once. Imagine your Facebook account rendering every story at once - it would never load!
当您在本地确定所有元素的高度时,使用ScrollView
此设置将起作用-例如,页面的高度将始终设置为相同。 如果传入的数据会影响内容的尺寸,则可能很难确定ScrollView
的尺寸。 有多种方法可以弥补这一点,但是ScrollView
更大限制是它可以一次渲染所有内容。 想象一下您的Facebook帐户一次渲染每个故事-它永远不会加载!
FlatList
is similar to ScrollView
, but it uses lazy-loading, so that only the items which are currently on the screen will render. Of course, FlatList
requires data to be passed to it. More specifically, it requires an array of data to be passed. Then, FlatList
loops over that array and renders each one when on screen. If an item goes off the screen, when the user scrolls away, FlatList
dumps that item and recreates it the next time it appears on the screen (state is lost). ScrollView
, on the other hand, doesn’t dump and reload, but renders them all at once at the beginning.
FlatList
与ScrollView
相似,但是它使用延迟加载,因此仅呈现当前在屏幕上的项目。 当然, FlatList
需要将数据传递给它。 更具体地说,它需要传递数据数组。 然后, FlatList
在该数组上循环并在屏幕上呈现每个数组。 如果某个项目不在屏幕上,则当用户滚动离开时, FlatList
转储该项目,并在下次它出现在屏幕上(状态丢失)时重新创建它。 另一方面, ScrollView
不会转储和重新加载,而是在开始时立即全部呈现。
Here is an example of each:
这是每个示例:
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>// content in here to fill the page</ScrollView>
</SafeAreaView>
<SafeAreaView style={{ flex: 1 }}>
<FlatList
data={dataArray}
renderItem={(
{ item } // item would represent one element in the dataArray
) => <IndividualComponent prop={item.prop} />}
keyExtractor={item => item.id}
/>
</SafeAreView>
Now, you wouldn’t ever want to nest FlatList
inside a ScrollView
or vice-versa. That isn’t good practice and it would give you an error anyhow. The important thing to keep in mind with FlatList is that the renderItem
prop is fixed to take these parameters in its function: renderItem={({item, index, separators}) => {}}
. Also, the item is always from the array you pass into the data
prop - which can only take in a plain array.
现在,您永远不需要将FlatList
嵌套在ScrollView
内,反之亦然。 这不是一个好习惯,无论如何都会给您带来错误。 FlatList要牢记的重要一点是, renderItem
已被固定为在其函数中采用以下参数: renderItem={({item, index, separators}) => {}}
。 同样,该项始终来自传递给data
属性的数组-只能接受一个普通数组。
A few other important things about FlatList - keyExtractor
takes care of React’s need to set a unique key on each element, just like setting a key
prop on each of the components rendered by FlatList. Also, if the dataArray
updates because of state or another prop, the FlatList wouldn’t re-render as it is setup in the example above. In order to have it update, you could set the extraData
prop to watch what would update (e.g. extraData={this.state}
).
有关FlatList的其他一些重要事项-keyExtractor keyExtractor
了React在每个元素上设置唯一键的需求,就像在FlatList呈现的每个组件上设置key
道具一样。 另外,如果dataArray
由于状态或其他属性而更新,则FlatList不会重新渲染,因为它是在上面的示例中设置的。 为了更新它,您可以设置extraData
来观察将要更新的内容(例如extraData={this.state}
)。
结语 (Wrap Up)
That concludes the basic components of React Native. As you can see, they are much more particular than you might be used to. For more information on the components here, check out the official docs.
到此为止,React Native的基本组成部分已经到了。 如您所见,它们比您习惯的要特殊得多。 有关此处组件的更多信息,请查看官方文档 。
翻译自: https://www.digitalocean.com/community/tutorials/react-react-native-basic-components