Skip to main content

学习基础知识

React Native 与 React 类似,但它使用原生组件而不是 Web 组件作为构建块。因此,要了解 React Native 应用的基本结构,你需要了解一些基本的 React 概念,例如 JSX、组件、stateprops。如果你已经了解 React,你仍然需要学习一些 React Native 特定的东西,比如原生组件。本教程面向所有受众,无论你是否有 React 经验。

¥React Native is like React, but it uses native components instead of web components as building blocks. So to understand the basic structure of a React Native app, you need to understand some of the basic React concepts, like JSX, components, state, and props. If you already know React, you still need to learn some React Native specific stuff, like the native components. This tutorial is aimed at all audiences, whether you have React experience or not.

我们来做这件事吧。

¥Let's do this thing.

你好世界

¥Hello World

按照我们人民的古老传统,我们首先必须构建一个除了说 "你好世界!" 之外什么都不做的应用。这里是:

¥In accordance with the ancient traditions of our people, we must first build an app that does nothing except say "Hello, world!". Here it is:

如果你感到好奇,可以直接在 Web 模拟器中使用示例代码。你还可以将其粘贴到 App.js 文件中,以在本地计算机上创建真正的应用。

¥If you are feeling curious, you can play around with sample code directly in the web simulators. You can also paste it into your App.js file to create a real app on your local machine.

这里发生了什么?

¥What's going on here?

  1. 首先,我们需要导入 React 才能使用 JSX,然后将其转换为各个平台的原生组件。

    ¥First of all, we need to import React to be able to use JSX, which will then be transformed to the native components of each platform.

  2. 在第 2 行,我们从 react-native 导入 TextView 组件

    ¥On line 2, we import the Text and View components from react-native

然后我们定义 HelloWorldApp 函数,它是 功能组件,其行为方式与 Web 版 React 中相同。该函数返回一个具有某些样式的 View 组件,并返回 aText 作为其子组件。

¥Then we define the HelloWorldApp function, which is a functional component and behaves in the same way as in React for the web. This function returns a View component with some styles and aText as its child.

Text 组件允许我们渲染文本,而 View 组件则渲染容器。该容器应用了多种样式,让我们分析一下每种样式的用途。

¥The Text component allows us to render a text, while the View component renders a container. This container has several styles applied, let's analyze what each one is doing.

我们找到的第一个样式是 flex: 1flex 属性将定义你的物品如何在沿主轴的可用空间上到达 "fill"。由于我们只有一个容器,因此它将占用父组件的所有可用空间。在本例中,它是唯一的组件,因此它将占用所有可用的屏幕空间。

¥The first style that we find is flex: 1, the flex prop will define how your items are going to "fill" over the available space along your main axis. Since we only have one container, it will take all the available space of the parent component. In this case, it is the only component, so it will take all the available screen space.

以下样式为 justifyContent:"center"。这会将容器的子级对齐到容器主轴的中心。最后,我们有 alignItems:"center",将容器的子级对齐到容器横轴的中心。

¥The following style is justifyContent: "center". This aligns children of a container in the center of the container's main axis. Finally, we have alignItems: "center", which aligns children of a container in the center of the container's cross axis.

这里的一些东西对你来说可能看起来不像 JavaScript。不要恐慌。这就是未来。

¥Some of the things in here might not look like JavaScript to you. Don't panic. This is the future.

首先,ES2015(也称为 ES6)是对 JavaScript 的一组改进,现已成为官方标准的一部分,但尚未得到所有浏览器的支持,因此通常尚未在 Web 开发中使用。React Native 附带了 ES2015 支持,因此你可以使用这些东西而不必担心兼容性。上例中的 importexportconstfrom 都是 ES2015 功能。如果你不熟悉 ES2015,你可能可以通过阅读本教程中的示例代码来了解它。如果你愿意,这一页 对 ES2015 功能有很好的概述。

¥First of all, ES2015 (also known as ES6) is a set of improvements to JavaScript that is now part of the official standard, but not yet supported by all browsers, so often it isn't used yet in web development. React Native ships with ES2015 support, so you can use this stuff without worrying about compatibility. import, export, const and from in the example above are all ES2015 features. If you aren't familiar with ES2015, you can probably pick it up by reading through sample code like this tutorial has. If you want, this page has a good overview of ES2015 features.

此代码示例中另一个不寻常的事情是 <View><Text>Hello world!</Text></View>。这是 JSX - 在 JavaScript 中嵌入 XML 的语法。许多框架使用专门的模板语言,它允许你将代码嵌入到标记语言中。在 React 中,情况正好相反。JSX 允许你在代码中编写标记语言。它看起来像 Web 上的 HTML,只不过你使用的是 React 组件,而不是像 <div><span> 这样的 Web 内容。在本例中,<Text> 是显示一些文本的 核心组件,而 View 类似于 <div><span>

¥The other unusual thing in this code example is <View><Text>Hello world!</Text></View>. This is JSX - a syntax for embedding XML within JavaScript. Many frameworks use a specialized templating language which lets you embed code inside markup language. In React, this is reversed. JSX lets you write your markup language inside code. It looks like HTML on the web, except instead of web things like <div> or <span>, you use React components. In this case, <Text> is a Core Component that displays some text and View is like the <div> or <span>.

组件

¥Components

所以这段代码定义了 HelloWorldApp,一个新的 Component。当你构建 React Native 应用时,你将制作很多新组件。你在屏幕上看到的任何内容都是某种组件。

¥So this code is defining HelloWorldApp, a new Component. When you're building a React Native app, you'll be making new components a lot. Anything you see on the screen is some sort of component.

属性

¥Props

大多数组件在创建时都可以使用不同的参数进行自定义。这些创建参数称为 props。

¥Most components can be customized when they are created, with different parameters. These creation parameters are called props.

你自己的组件也可以使用 props。这使你可以创建一个在应用中的许多不同位置使用的单个组件,每个位置的属性略有不同。请参阅功能组件中的 props.YOUR_PROP_NAME 或类组件中的 this.props.YOUR_PROP_NAME。这是一个例子:

¥Your own components can also use props. This lets you make a single component that is used in many different places in your app, with slightly different properties in each place. Refer to props.YOUR_PROP_NAME in your functional components or this.props.YOUR_PROP_NAME in your class components. Here's an example:

使用 name 作为 prop 可以让我们自定义 Greeting 组件,这样我们就可以为每个问候语重用该组件。此示例还使用了 JSX 中的 Greeting 组件。做到这一点的能力让 React 如此酷。

¥Using name as a prop lets us customize the Greeting component, so we can reuse that component for each of our greetings. This example also uses the Greeting component in JSX. The power to do this is what makes React so cool.

这里发生的另一个新事物是 View 组件。View 可用作其他组件的容器,以帮助控制样式和布局。

¥The other new thing going on here is the View component. A View is useful as a container for other components, to help control style and layout.

使用 props 和基本的 TextImageView 组件,你可以构建各种静态屏幕。要了解如何使你的应用随时间变化,你需要 了解状态

¥With props and the basic Text, Image, and View components, you can build a wide variety of static screens. To learn how to make your app change over time, you need to learn about State.

状态

¥State

与属性 是只读的 不同且不应修改,state 允许 React 组件随着时间的推移更改其输出,以响应用户操作、网络响应和其他任何内容。

¥Unlike props that are read-only and should not be modified, the state allows React components to change their output over time in response to user actions, network responses and anything else.

React 中的 state 和 props 有什么区别?

¥What's the difference between state and props in React?

在 React 组件中,props 是我们从父组件传递给子组件的变量。同样,状态也是变量,不同之处在于它们不是作为参数传递,而是由组件在内部初始化和管理它们。

¥In a React component, the props are the variables that we pass from a parent component to a child component. Similarly, the state are also variables, with the difference that they are not passed as parameters, but rather that the component initializes and manages them internally.

React 和 React Native 在处理状态方面有区别吗?

¥Are there differences between React and React Native to handle the state?

// ReactJS Counter Example using Hooks!

import React, {useState} from 'react';



const App = () => {
const [count, setCount] = useState(0);

return (
<div className="container">
<p>You clicked {count} times</p>
<button
onClick={() => setCount(count + 1)}>
Click me!
</button>
</div>
);
};


// CSS
.container {
display: flex;
justify-content: center;
align-items: center;
}

// React Native Counter Example using Hooks!

import React, {useState} from 'react';
import {View, Text, Button, StyleSheet} from 'react-native';

const App = () => {
const [count, setCount] = useState(0);

return (
<View style={styles.container}>
<Text>You clicked {count} times</Text>
<Button
onPress={() => setCount(count + 1)}
title="Click me!"
/>
</View>
);
};

// React Native Styles
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});

如上所示,ReactReact Native 在处理 state 上没有区别。你可以使用 hooks! 在类和功能组件中使用组件的状态。

¥As shown above, there is no difference in handling the state between React and React Native. You can use the state of your components both in classes and in functional components using hooks!

在下面的示例中,我们将使用类展示与上述相同的计数器示例。

¥In the following example we will show the same above counter example using classes.