React Native Hello World

摘要:在本教程中,您将学习如何创建第一个名为 Hello World 的 React Native 应用程序。

先决条件

本教程假设您已在计算机上设置 React Native 开发环境,并在手机上安装了 Expo Go 应用程序。

创建新的 React Native 项目

我们将使用 create-expo-app 命令创建一个新的 Expo 和 React Native 项目。此 create-expo-app 工具使您可以使用模板快速初始化项目。

步骤 1. 打开您的终端并运行以下命令以创建一个名为 helloworld 的新项目

npx create-expo-app helloworld --template blankCode language: plaintext (plaintext)

在此命令中

  • create-expo-app 命令为项目创建 helloworld 目录。
  • --template blank 选项指示命令安装所有必需的软件包并初始化一个空白的 React Native 项目。

步骤 2. 导航到项目目录

cd helloworldCode language: plaintext (plaintext)

步骤 3. 使用以下命令从终端运行应用程序

npm startCode language: plaintext (plaintext)

npm start 将执行 npx expo start 命令,该命令运行应用程序。它将返回以下输出

React Native Hello World - Expo

请注意,您的二维码可能有所不同。

步骤 4. 扫描二维码以在您的手机上启动应用程序。

使用内置相机扫描二维码后,Expo Go 将在您的手机上打开应用程序。您将在手机上看到以下消息出现

Open up App.js to start working on your app!Code language: CSS (css)

Hello World 应用程序

步骤 1. 使用您喜欢的代码编辑器打开项目目录。

步骤 2. 打开 App.js 文件并将代码更改为以下内容

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

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>Hello, World!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 40,
  }
});
Code language: JavaScript (javascript)

输出

它是如何工作的。

首先,从 react-native 库导入 StyleSheet、Text 和 View

import { View, Text, StyleSheet } from 'react-native';Code language: JavaScript (javascript)

在此语法中,我们从 react-native 库导入三个对象

  • View 是 React Native 中用于构建用户界面 (UI) 的基本组件。View 的作用类似于 HTML 中的 div 元素,它们用作包装其他组件的容器。在幕后,React Native 将 View 组件直接转换为 Android (android.View) 和 iOS (UIView) 上的本机视图。
  • Text 是用于显示文本的核心组件。
  • StyleSheet 创建一个类似于 CSS Stylesheet 的对象。

其次,创建一个 App 组件,它返回一段 JSX 并使用默认导出导出它。

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>Hello, World!</Text>
    </View>
  );
}Code language: JavaScript (javascript)

与 React 一样,React Native 中的组件是一个函数,它返回一些JSX

在此示例中,App 函数返回一个包含带有文本 Hello, World!TextView。View 和 Text 组件都具有一个名为 style 的道具,它接受来自 styles 对象的值。

第三,使用 StyleSheet 中的 create() 函数定义 styles 对象

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 40,
  }
});Code language: JavaScript (javascript)

create() 函数中,我们定义了一个具有两个属性 containertext 的对象,它们的值是 JavaScript 对象,其作用类似于 CSS,定义了组件的外观和感觉。

  • container 属性使用 flex: 1justifyContent: centeralignItems: center 将其子组件放置在中心,在本例中,是屏幕的中心。
  • text 属性指定字体大小为 40,这将 Text 组件的字体大小设置为 40。

如果您保存文件并打开 Expo Go,您将在手机上看到即时更新。消息更改为以下内容

Hello, World!

此功能称为热重载,有助于加快开发速度,使您能够更改代码并立即在应用程序中看到 UI 更改。

总结

  • 运行 npx create-expo-app project-name --template blank 以创建名为 project-name 的 React Native 项目。
  • 执行 npm start 以启动应用程序并扫描二维码以使用 Expo Go 应用程序在手机上启动应用程序。
本教程是否有帮助?