React 基础知识
React Native 运行在 React 上,React 是一个流行的开源库,用于使用 JavaScript 构建用户界面。为了充分利用 React Native,了解 React 本身会有所帮助。本部分可以帮助你入门,也可以作为复习课程。
¥React Native runs on React, a popular open source library for building user interfaces with JavaScript. To make the most of React Native, it helps to understand React itself. This section can get you started or can serve as a refresher course.
我们将介绍 React 背后的核心概念:
¥We’re going to cover the core concepts behind React:
-
components
-
JSX
-
props
-
state
如果你想深入了解,我们鼓励你查看 React 官方文档。
¥If you want to dig deeper, we encourage you to check out React’s official documentation.
你的第一个组件
¥Your first component
React 介绍的其余部分在示例中使用了猫:友好、平易近人的生物需要名字和咖啡馆才能工作。这是你的第一个 Cat 组件:
¥The rest of this introduction to React uses cats in its examples: friendly, approachable creatures that need names and a cafe to work in. Here is your very first Cat component:
操作方法如下:要定义 Cat
组件,首先使用 JavaScript 的 import
导入 React 和 React Native 的 Text
核心组件:
¥Here is how you do it: To define your Cat
component, first use JavaScript’s import
to import React and React Native’s Text
Core Component:
import React from 'react';
import {Text} from 'react-native';
你的组件作为一个函数开始:
¥Your component starts as a function:
const Cat = () => {};
你可以将组件视为蓝图。函数组件返回的任何内容都会渲染为 React 元素。React 元素可让你描述你希望在屏幕上看到的内容。
¥You can think of components as blueprints. Whatever a function component returns is rendered as a React element. React elements let you describe what you want to see on the screen.
这里 Cat
组件将渲染 <Text>
元素:
¥Here the Cat
component will render a <Text>
element:
const Cat = () => {
return <Text>Hello, I am your cat!</Text>;
};
你可以使用 JavaScript 的 export default
导出函数组件,以便在整个应用中使用,如下所示:
¥You can export your function component with JavaScript’s export default
for use throughout your app like so:
const Cat = () => {
return <Text>Hello, I am your cat!</Text>;
};
export default Cat;
这是导出组件的多种方法之一。这种导出与 Snack Player 配合良好。但是,根据应用的文件结构,你可能需要使用不同的约定。这个 JavaScript 导入和导出的便捷备忘单 可以提供帮助。
¥This is one of many ways to export your component. This kind of export works well with the Snack Player. However, depending on your app’s file structure, you might need to use a different convention. This handy cheatsheet on JavaScript imports and exports can help.
现在仔细看看 return
声明。<Text>Hello, I am your cat!</Text>
使用一种 JavaScript 语法,可以方便地编写元素:JSX。
¥Now take a closer look at that return
statement. <Text>Hello, I am your cat!</Text>
is using a kind of JavaScript syntax that makes writing elements convenient: JSX.
JSX
React 和 React Native 使用 JSX,这种语法允许你在 JavaScript 中编写元素,如下所示:<Text>Hello, I am your cat!</Text>
。React 文档有 JSX 综合指南,你可以参考了解更多信息。因为 JSX 是 JavaScript,所以你可以在其中使用变量。在这里,你为猫声明了一个名称 name
,并用大括号将其嵌入到 <Text>
中。
¥React and React Native use JSX, a syntax that lets you write elements inside JavaScript like so: <Text>Hello, I am your cat!</Text>
. The React docs have a comprehensive guide to JSX you can refer to learn even more. Because JSX is JavaScript, you can use variables inside it. Here you are declaring a name for the cat, name
, and embedding it with curly braces inside <Text>
.
任何 JavaScript 表达式都可以在大括号之间工作,包括像 {getFullName("Rum", "Tum", "Tugger")}
这样的函数调用:
¥Any JavaScript expression will work between curly braces, including function calls like {getFullName("Rum", "Tum", "Tugger")}
:
- TypeScript
- JavaScript
你可以将大括号视为在 JSX 中创建 JS 功能的门户!
¥You can think of curly braces as creating a portal into JS functionality in your JSX!
因为 JSX 包含在 React 库中,所以如果文件顶部没有
import React from 'react'
,它将无法工作!¥Because JSX is included in the React library, it won’t work if you don’t have
import React from 'react'
at the top of your file!
定制组件
¥Custom Components
你已经认识了 React Native 的核心组件。React 允许你将这些组件嵌套在一起以创建新组件。这些可嵌套、可重用的组件是 React 范例的核心。
¥You’ve already met React Native’s Core Components. React lets you nest these components inside each other to create new components. These nestable, reusable components are at the heart of the React paradigm.
例如,你可以将 Text
和 TextInput
嵌套在下面的 View
中,React Native 会将它们渲染在一起:
¥For example, you can nest Text
and TextInput
inside a View
below, and React Native will render them together:
开发者注意事项
¥Developer notes
- Android
- Web
如果你熟悉 Web 开发,
<View>
和<Text>
可能会让你想起 HTML!你可以将它们视为应用开发的<div>
和<p>
标签。¥If you’re familiar with web development,
<View>
and<Text>
might remind you of HTML! You can think of them as the<div>
and<p>
tags of application development.
在 Android 上,你通常将视图放在
LinearLayout
、FrameLayout
、RelativeLayout
等内部,以定义视图的子视图在屏幕上的排列方式。在 React Native 中,View
使用 Flexbox 作为其子级布局。你可以在 我们的 Flexbox 布局指南 中了解更多信息。¥On Android, you usually put your views inside
LinearLayout
,FrameLayout
,RelativeLayout
, etc. to define how the view’s children will be arranged on the screen. In React Native,View
uses Flexbox for its children’s layout. You can learn more in our guide to layout with Flexbox.
你可以使用 <Cat>
在多个位置多次渲染此组件,而无需重复代码:
¥You can render this component multiple times and in multiple places without repeating your code by using <Cat>
:
任何渲染其他组件的组件都是父组件。这里,Cafe
是父组件,每个 Cat
是子组件。
¥Any component that renders other components is a parent component. Here, Cafe
is the parent component and each Cat
is a child component.
你可以在咖啡馆里放置任意数量的猫。每个 <Cat>
都会渲染一个独特的元素 - 你可以使用属性对其进行自定义。
¥You can put as many cats in your cafe as you like. Each <Cat>
renders a unique element—which you can customize with props.
属性
¥Props
Props 是“属性”的缩写。Props 让你可以自定义 React 组件。例如,这里为每个 <Cat>
传递一个不同的 name
以供 Cat
渲染:
¥Props is short for “properties”. Props let you customize React components. For example, here you pass each <Cat>
a different name
for Cat
to render:
- TypeScript
- JavaScript
大多数 React Native 的核心组件也可以使用 props 进行定制。例如,当使用 Image
时,你可以向它传递一个名为 source
的 prop 来定义它显示的图片:
¥Most of React Native’s Core Components can be customized with props, too. For example, when using Image
, you pass it a prop named source
to define what image it shows:
Image
有 许多不同的属性,包括 style
,它接受设计和布局相关的属性值对的 JS 对象。
¥Image
has many different props, including style
, which accepts a JS object of design and layout related property-value pairs.
请注意包围
style
宽度和高度的双大括号{{ }}
。在 JSX 中,JavaScript 值通过{}
引用。如果你传递字符串以外的其他内容作为属性(例如数组或数字),这会很方便:<Cat food={["fish", "kibble"]} age={2} />
。然而,JS 对象也用大括号表示:{width: 200, height: 200}
。因此,要在 JSX 中传递 JS 对象,必须将该对象括在另一对大括号中:{{width: 200, height: 200}}
¥Notice the double curly braces
{{ }}
surroundingstyle
‘s width and height. In JSX, JavaScript values are referenced with{}
. This is handy if you are passing something other than a string as props, like an array or number:<Cat food={["fish", "kibble"]} age={2} />
. However, JS objects are also denoted with curly braces:{width: 200, height: 200}
. Therefore, to pass a JS object in JSX, you must wrap the object in another pair of curly braces:{{width: 200, height: 200}}
你可以使用属性和核心组件 Text
、Image
和 View
构建许多东西!但要构建交互式的东西,你需要状态。
¥You can build many things with props and the Core Components Text
, Image
, and View
! But to build something interactive, you’ll need state.
状态
¥State
虽然你可以将 props 视为用于配置组件渲染方式的参数,但状态就像组件的个人数据存储。状态对于处理随时间变化的数据或来自用户交互的数据非常有用。状态为你的组件提供记忆!
¥While you can think of props as arguments you use to configure how components render, state is like a component’s personal data storage. State is useful for handling data that changes over time or that comes from user interaction. State gives your components memory!
作为一般规则,在渲染时使用 props 来配置组件。使用状态来跟踪你期望随时间变化的任何组件数据。
¥As a general rule, use props to configure a component when it renders. Use state to keep track of any component data that you expect to change over time.
下面的例子发生在一家猫咖啡馆,两只饥饿的猫正在等待喂食。他们的饥饿感,我们期望随着时间的推移而改变(与他们的名字不同),被存储为状态。要喂猫,请按下它们的按钮,这将更新它们的状态。
¥The following example takes place in a cat cafe where two hungry cats are waiting to be fed. Their hunger, which we expect to change over time (unlike their names), is stored as state. To feed the cats, press their buttons—which will update their state.
你可以通过调用 React 的 useState
Hook 向组件添加状态。Hook 是一种让你“钩子”React 功能的函数。例如,useState
是一个 Hook,可让你向功能组件添加状态。你可以了解更多关于 React 文档中的其他类型的 Hooks。 的信息
¥You can add state to a component by calling React’s useState
Hook. A Hook is a kind of function that lets you “hook into” React features. For example, useState
is a Hook that lets you add state to function components. You can learn more about other kinds of Hooks in the React documentation.
- TypeScript
- JavaScript
首先,你需要从 React 导入 useState
,如下所示:
¥First, you will want to import useState
from React like so:
import React, {useState} from 'react';
然后,通过在其函数内调用 useState
来声明组件的状态。在此示例中,useState
创建了 isHungry
状态变量:
¥Then you declare the component’s state by calling useState
inside its function. In this example, useState
creates an isHungry
state variable:
const Cat = (props: CatProps) => {
const [isHungry, setIsHungry] = useState(true);
// ...
};
你可以使用
useState
跟踪任何类型的数据:字符串、数字、布尔值、数组、对象。例如,你可以追踪一只猫被const [timesPetted, setTimesPetted] = useState(0)
抚摸的次数!¥You can use
useState
to track any kind of data: strings, numbers, Booleans, arrays, objects. For example, you can track the number of times a cat has been petted withconst [timesPetted, setTimesPetted] = useState(0)
!
调用 useState
会做两件事:
¥Calling useState
does two things:
-
它创建一个具有初始值的“状态变量” - 在本例中,状态变量是
isHungry
,其初始值是true
¥it creates a “state variable” with an initial value—in this case the state variable is
isHungry
and its initial value istrue
-
它创建一个函数来设置该状态变量的值 -
setIsHungry
¥it creates a function to set that state variable’s value—
setIsHungry
你使用什么名称并不重要。但将模式视为 [<getter>, <setter>] = useState(<initialValue>)
会更方便。
¥It doesn’t matter what names you use. But it can be handy to think of the pattern as [<getter>, <setter>] = useState(<initialValue>)
.
接下来添加 Button
核心组件并为其指定 onPress
属性:
¥Next you add the Button
Core Component and give it an onPress
prop:
<Button
onPress={() => {
setIsHungry(false);
}}
//..
/>
现在,当有人按下按钮时,onPress
将触发,调用 setIsHungry(false)
。这会将状态变量 isHungry
设置为 false
。当 isHungry
为 false 时,Button
的 disabled
属性设置为 true
,其 title
也会更改:
¥Now, when someone presses the button, onPress
will fire, calling the setIsHungry(false)
. This sets the state variable isHungry
to false
. When isHungry
is false, the Button
’s disabled
prop is set to true
and its title
also changes:
<Button
//..
disabled={!isHungry}
title={isHungry ? 'Give me some food, please!' : 'Thank you!'}
/>
你可能已经注意到,虽然
isHungry
是 const,但它似乎可以重新分配!发生的情况是,当调用像setIsHungry
这样的状态设置函数时,其组件将重新渲染。在这种情况下,Cat
函数将再次运行,这一次,useState
将为我们提供isHungry
的下一个值。¥You might’ve noticed that although
isHungry
is a const, it is seemingly reassignable! What is happening is when a state-setting function likesetIsHungry
is called, its component will re-render. In this case theCat
function will run again—and this time,useState
will give us the next value ofisHungry
.
最后,将你的猫放入 Cafe
组件中:
¥Finally, put your cats inside a Cafe
component:
const Cafe = () => {
return (
<>
<Cat name="Munkustrap" />
<Cat name="Spot" />
</>
);
};
看到上面的
<>
和</>
了吗?JSX 的这些位是 fragments。相邻的 JSX 元素必须包含在封闭标记中。片段让你无需嵌套额外的、不必要的封装元素(如View
)即可做到这一点。¥See the
<>
and</>
above? These bits of JSX are fragments. Adjacent JSX elements must be wrapped in an enclosing tag. Fragments let you do that without nesting an extra, unnecessary wrapping element likeView
.
现在你已经了解了 React 和 React Native 的核心组件,让我们通过查看 处理 <TextInput>
来更深入地了解其中一些核心组件。
¥Now that you’ve covered both React and React Native’s Core Components, let’s dive deeper on some of these core components by looking at handling <TextInput>
.