React Native教程:构建您的第一个React Native应用

This React Native tutorial is aimed at introducing React Native, giving you the basics of what you need to know before building a real React Native application. After that, we proceed to help you build your first real React Native app. By the end of this article, you will build a React Native app that can run on both iOS and Android devices.

本React Native教程旨在介绍React Native,为您提供构建真正的React Native应用程序之前需要了解的基础知识。 之后,我们将继续帮助您构建您的第一个真正的React Native应用程序。 到本文结尾,您将构建一个可在iOS和Android设备上运行的React Native应用程序。

React Native is a cross-platform development library built on top of React by Facebook, for mobile development platforms. React Native was developed in 2013 as a hackathon project inside Facebook and was later released for public use in 2015. It gained huge popularity in the developer community and multiple tech companies adopted it as a mobile development solution because React Native apps share a single codebase for both iOS and Android and could hardly be distinguished from truly native apps. According to the React Native website:

React Native是跨Facebook开发的跨平台开发库,用于移动开发平台。 React Native于2013年作为Facebook内的一个黑客马拉松项目开发,后来于2015年发布以供公众使用。它在开发人员社区中获得了广泛的欢迎,多家技术公司将其用作移动开发解决方案,因为React Native应用程序共享一个代码库,包括iOS和Android,很难与真正的本地应用程序区分开。 根据React Native网站的说法:

In 2018, React Native had the 2nd highest number of contributors for any repository in GitHub. Today, React Native is supported by contributions from individuals and companies around the world including Expo, and Microsoft.

在2018年,React Native 在GitHub中任何存储库的贡献者数量中 排名第二 如今,React Native得到了来自世界各地的个人和公司(包括 Expo Microsoft)的支持

Before we go ahead and build our first React Native app, I’m going to show you the pros and cons of React Native and more details on what it actually is.

在继续构建第一个React Native应用之前,我将向您展示React Native的优缺点,以及有关其实际含义的更多细节。

什么是React Native? (What is React Native?)

  • React Native is a hybrid mobile development library.

    React Native是一个混合移动开发库。
  • React Native apps are written in JSX and Javascript and compiled into native code.

    React Native应用程序是用JSX和Javascript编写的,并被编译成本机代码。
  • React Native apps contain 85–90% shared Javascript and JSX code

    React Native应用程序包含85–90%的共享Javascript和JSX代码

什么是React Native? (What is React Native not?)

  • React Native is not a webview

    React Native不是Webview
  • React Native is not React

    React Native不是React
  • React Native is not PWA

    React Native不是PWA
  • React Native as of this writing supports web development using React Native for Web

    在撰写本文时,React Native支持使用React Native for Web进行Web开发。

为什么要采用/学习React Native? (Why should you adopt/learn React Native?)

  • Targets multiple platforms (iOS, Android, Web, TVOS) with the same codebase and effort

    以相同的代码库和工作量针对多个平台(iOS,Android,Web,TVOS)
  • Has a large and growing community that is there to provide adequate support

    有一个庞大且不断发展的社区,可以提供足够的支持
  • Has native support meaning that you can customize the native code to suit your use-case/business logic

    具有本机支持,意味着您可以自定义本机代码以适合您的用例/业务逻辑
  • Requires knowledge of Javascript. Javascript is a language in high popular demand and learning it will pay off immensely

    需要Java知识。 Javascript是一种受欢迎程度很高的语言,学习它将会获得巨大回报
  • Has a feature which I personally refer to as the sweet spot: Fast Refresh (Hot Reloading)

    具有我个人称为最有效的功能:快速刷新(热加载)

React本机的缺点? (React Native Drawbacks?)

React Native has some drawbacks too, but the developers of the library are consistently trying to improve them as the community grows:

React Native也有一些缺点,但是随着社区的发展,该库的开发人员一直在努力改善它们:

  • While the codebase is mostly shared among various platform, knowledge of native development is sometimes required in developing more advanced React Native projects

    虽然代码库主要在各种平台之间共享,但是在开发更高级的React Native项目时有时需要原生开发知识
  • Despite the fact that most React Native apps look the same in appearance to native apps React Native seems to lack the smooth navigation achieved by native apps.

    尽管大多数React Native应用程序在外观上与本机应用程序相同,但React Native似乎缺乏本机应用程序实现的流畅导航。
  • React Native developers agree that React Native style of error reporting is not the best out there but they cope with it over time.

    React Native开发人员一致认为,React Native错误报告风格并不是目前最好的,但是随着时间的推移,他们会对其进行处理。

构建您的第一个React Native应用 (Build Your First React Native App)

Let’s build a React Native app to display a simple list of countries. The app will contain only one screen, and we are going to keep its functionality and styling to a minimum, since the purpose of this tutorial is to help you set up your React Native developer environment and dip your toes into the React Native programming language.

让我们构建一个React Native应用程序以显示简单的国家/地区列表。 该应用程序仅包含一个屏幕,并且我们将其功能和样式保持在最低限度,因为本教程的目的是帮助您设置React Native开发人员环境并将脚趾浸入React Native编程语言。

In this React Native tutorial we are going to use Expo in order to build your first React Native application. Expo is a powerful tool for those how are beginners in the React Native world, since it lets you run and preview React Native apps on your devices easily.

在本React Native教程中,我们将使用Expo来构建您的第一个React Native应用程序。 对于那些在React Native领域中的初学者来说,Expo是一个强大的工具,因为它使您可以轻松地在设备上运行和预览React Native应用。

1.安装Expo (1. Install Expo)

Follow the official documentation on how to install Expo. Once you’ve installed it, come back to this tutorial and follow the next steps in order to build your first React Native app.

请遵循有关如何安装Expo的官方文档。 安装后,请返回本教程并按照以下步骤操作,以构建您的第一个React Native应用程序。

2.创建一个新的React Native App (2. Create a New React Native App)

expo init firstapp

Select the ‘blank’ project

选择“ 空白 ”项目

Select ‘Y’ to work with yarn.

选择“ Y ”以处理纱线。

Yarn v1.19.2 found. Use Yarn to install dependencies? (Y/n)

Once you click Yes, Expo will work its magic and create all the necessary files for you. You can take a look at the directory structure to get an idea of what is going on in the project.

一旦单击“是”,Expo将发挥其魔力并为您创建所有必需的文件。 您可以看一下目录结构,以了解项目中正在发生的事情。

3.运行您的第一个React Native应用 (3. Run Your First React Native App)

Run the following commands to start your newly created React Native app:

运行以下命令以启动新创建的React Native应用程序:

cd firstapp yarn start

At this point, if you set up Expo properly at the previous steps, the new React Native project should have loaded successfully and you should be able to see the app as in the following screenshot:

此时,如果您在前面的步骤中正确设置了Expo,那么新的React Native项目应该已经成功加载,并且您应该能够看到该应用程序,如以下屏幕截图所示:

Image for post

There you have it, the very first React Native application that you’ve build. By default it says ‘ Open up App.js to start working on your app’ and I agree that it’s not the best welcome message Expo could offer but we’re going to go ahead and do as they say. Let’s open App.js file, which looks like this:

您已经有了它,这是您构建的第一个React Native应用程序。 默认情况下,它显示为“ 打开App.js以开始在您的应用上工作 ”,我同意这不是Expo可以提供的最好的欢迎信息,但我们将按照他们所说的去做。 让我们打开App.js文件,如下所示:

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

Now let me give a concise summary of what’s going on before we move on.

现在,让我在继续之前简要概述正在发生的事情。

  • The styles variable contains various style dicts of the components

    样式变量包含组件的各种样式指示
  • The Function App is a React Native Functional Component, the default one that renders what we currently see on our screen and above are import statements that import components to be used and composed to create our parent component App.

    Function App是一个React Native Functional Component,它是默认的渲染组件,用于呈现我们当前在屏幕上和上方看到的内容,这些import语句用于导入要使用并组成的用于创建父组件App的组件。

4.添加国家列表 (4. Add List of Countries)

Let’s move on and rewrite this dummy screen with our own UI. As we mentioned before, we are going to display a list of countries. For this, we need to implement the following:

让我们继续并使用我们自己的UI重写此虚拟屏幕。 如前所述,我们将显示国家列表。 为此,我们需要实现以下内容:

import React from 'react';
import { StyleSheet, Text, FlatList } from 'react-native';
export default function App() {
const countriesData = [{"name":"Afghanistan"},{"name":"Åland Islands"},{"name":"Albania"},{"name":"Algeria"}]
return (
<FlatList
data={countriesData}
contentContainerStyle={styles.container}
keyExtractor={item => item.name}
renderItem={({item})=> <Text style={styles.text}>{item.name}</Text>}
/>
);
}
const styles = StyleSheet.create({
container: {
paddingTop: 30,
},
text: {
fontSize: 20,
margin: 10
},
});

As you can see, we have updated our App.js and added a few things:

如您所见,我们已经更新了App.js并添加了一些内容:

  • A Flatlist to display the list of countries

    一个Flatlist,显示国家的名单

  • A dummy dataset to display to be displayed on the list

    要显示在列表上的虚拟数据集
  • We updated the style object to contain the style for our text

    我们更新了样式对象以包含文本的样式

Run your app if you haven’t started it already, and you should be seeing this:

如果尚未启动应用程序,请运行它,并且应该会看到以下信息:

Image for post

We now have something to work with. But the data is static and we would like a longer dynamic list, that can change and we need those changes to be reflected in the UI. So we need the UI to be “reactive” to the changes in the data model. This is the core concept of React, and therefore React Native. So we need to introduce the State concept.

现在,我们需要处理一些事情。 但是数据是静态的,我们想要更长的动态列表,它可以更改,我们需要将这些更改反映在UI中。 因此,我们需要UI对数据模型的更改“ React式 ”。 这是React的核心概念,因此也是React Native的核心概念。 因此,我们需要介绍国家概念。

A React Native component holds data in its state, and whenever the state changes, the UI is re-rendered to reflect those changes. Let’s add a state variable, named countriesData which will store the dynamic list of countries displayed on the screen.

React Native组件将数据保持在其状态中,并且只要状态发生更改,UI就会重新呈现以反映这些更改。 让我们添加一个名为countriesData的状态变量,该变量将存储屏幕上显示的国家的动态列表。

const [countriesData, setCountriesData] = useState([])

The useState is called a “hook” in React Native. According to official React documentation on hooks

useState在React Native中被称为“挂钩”。 根据有关钩子的官方React 文档

A Hook is a special function that lets you “hook into” React features

挂钩是一项特殊功能,可让您“挂钩” React功能

We just declared a state for our app countriesData with default value as an empty array [] and a function setCountriesData to update the value of countriesData. For example, calling setCountriesData([1,2,3,]) will update the value of countriesData to [1,2,3,].

我们刚刚宣布的状态我们使用默认值作为空数组[]和功能setCountriesData更新countriesData的价值应用countriesData。 例如,调用setCountriesData([1,2,3,])将更新countriesData至[1,2,3,]的值。

Another important hook useEffect is going to be applied in the following code snippet. Simply put, any code written inside the useEffect runs when the component is mounted.

另一个重要的钩子useEffect将在以下代码段中应用。 简而言之,当组件被安装时,在useEffect中编写的任何代码都将运行。

import React, {useState, useEffect} from 'react';
import { StyleSheet, Text, FlatList, Pressable, Alert } from 'react-native';
import { StatusBar } from 'expo-status-bar';
export default function App() {
const [countriesData, setCountriesData] = useState([])
function fetchCountriesData() {
fetch('https://restcountries.eu/rest/v2/region/africa?fields=name;capital')
.then((response) => response.json())
.then((json) => setCountriesData(json))
.catch((error) => console.error(error))
}
useEffect(()=> {
fetchCountriesData();
})
return (
<>
<StatusBar style='light'/>
<FlatList
data={countriesData}
contentContainerStyle={styles.container}
keyExtractor={item => item.name}
renderItem={({item})=> <Text onPress={() => {Alert.alert(`The Capital of ${item.name} is ${item.capital}`)}} style={styles.text}>{item.name}</Text>}
/>
</>
);
}
const styles = StyleSheet.create({
container: {
paddingTop: 30,
backgroundColor: '#483D8B'
},
text: {
fontSize: 18,
margin: 5,
color: '#fff'
},
});

Please don’t be scared of what’s going on. We are using the fetch API to retrieve countries data from an API endpoint and display a list of African countries. The fetch API is how you make network requests in React Native. As you can notice, we’ve used a free API endpoint, exposed on the restcountries.eu website. This returns a JSON object, parsed in the then() clause of the fetch method. Once parsed successfully, we update the countriesData state variable with the new list of country, newly retrieved. As a result of updating the state object, the UI also gets re-rendered and we can see the countries on the screen:

请不要害怕发生了什么。 我们正在使用访存API从API端点检索国家/地区数据并显示非洲国家/地区列表。 提取API是您在React Native中发出网络请求的方式。 如您所见 ,我们使用了一个免费的API端点,该端点公开于restcountries.eu网站。 这将返回一个JSON对象,该对象在fetch方法的then()子句中进行了解析。 成功解析后,我们将使用新获取的国家/地区新列表更新countryData状态变量。 更新状态对象的结果是,UI也被重新渲染,我们可以在屏幕上看到国家/地区:

5.设计您的第一个React Native应用程序 (5. Styling Your First React Native App)

Let’s now focus on making the design of the app slightly better, since we already have the core functionality in place. We are going to focus on styling the app and our focus is on the styles dictionary.

现在,让我们专注于使应用程序的设计稍微好一些,因为我们已经具备了核心功能。 我们将专注于样式化应用程序,而我们专注于样式字典。

import React, {useState, useEffect} from 'react';
import { StyleSheet, Text, FlatList, Pressable, Alert } from 'react-native';
import { StatusBar } from 'expo-status-bar';
export default function App() {
const [countriesData, setCountriesData] = useState([])
function fetchCountriesData() {
fetch('https://restcountries.eu/rest/v2/region/africa?fields=name;capital')
.then((response) => response.json())
.then((json) => setCountriesData(json))
.catch((error) => console.error(error))
}
useEffect(()=> {
fetchCountriesData();
})
return (
<>
<StatusBar style='light'/>
<FlatList
data={countriesData}
contentContainerStyle={styles.container}
keyExtractor={item => item.name}
renderItem={({item})=> <Text onPress={() => {Alert.alert(`The Capital of ${item.name} is ${item.capital}`)}} style={styles.text}>{item.name}</Text>}
/>
</>
);
}
const styles = StyleSheet.create({
container: {
paddingTop: 30,
backgroundColor: '#483D8B'
},
text: {
fontSize: 18,
margin: 5,
color: '#fff'
},
});

As you can see, we’ve changed the color of the background to purple, by providing the backgroundColor attribute with ‘#483D8B’ hex code.

如您所见,通过为backgroundColor属性提供'#483D8B'十六进制代码,我们将背景色更改为紫色。

While the syntax is very similar to CSS, it is slightly different. But the core concepts are the same, so if you already know CSS, learning how to style React Native apps will be extremely easy. Especially if you are already familiar with flexbox layout.

虽然语法与CSS非常相似,但略有不同。 但是核心概念是相同的,因此,如果您已经了解CSS,那么学习如何设计React Native应用程序样式将非常容易。 特别是如果您已经熟悉flexbox布局

Image for post

结论 (Conclusion)

We saw what are the biggest sell points for using React Native in your mobile development process, and how easy it is to create apps for both iOS and Android.

我们看到了在移动开发过程中使用React Native的最大卖点是什么,以及为iOS和Android创建应用程序有多么容易。

We’ve set up Expo, which is an amazing tool for beginners who are new to the React Native world. We then leveraged Expo to create our first React Native project.

我们已经设置了Expo,对于刚接触React Native的初学者来说,这是一个了不起的工具。 然后,我们利用Expo来创建我们的第一个React Native项目。

After that, we learned about functional components, hooks and state. We’ve used the fetch API to retrieve data via a network request, and we styled the visual components by modifying the stylesheet.

之后,我们学习了功能组件,挂钩和状态。 我们已经使用fetch API通过网络请求检索数据,并且通过修改样式表来设置可视化组件的样式。

Congratulations! You were able to build a React Native app. Now it’s time to learn more advanced concepts, in order to add more complex functionalities and develop fully functional mobile apps, that you can publish to the App Store and Google Play Store. Check out this list of the best React Native resources to learn more about React Native and dive into the next level.

恭喜你! 您能够构建一个React Native应用程序。 现在是时候学习更高级的概念,以添加更多复杂的功能并开发功能齐全的移动应用程序,您可以将其发布到App Store和Google Play商店中。 查看最佳React Native最佳资源列表,以了解有关React Native的更多信息并进入下一个层次。

下一步 (Next Steps)

Now that you have learned about best React Native development tools, here are some other topics you can look into

现在您已经了解了最佳的React Native开发工具,下面是您可以研究的其他一些主题

If you need a base to start your next React Native app, you can save months of development by leveraging one of our React Native templates.

如果您需要基础来启动下一个React Native应用程序,则可以利用我们的React Native模板之一节省数月的开发时间。

Originally published at https://www.instamobile.io on July 24, 2020.

最初于 2020年7月24日 https://www.instamobile.io 发布

翻译自: https://medium.com/javascript-in-plain-english/react-native-tutorial-build-your-first-react-native-app-af66345c5e63

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值