摘要:在本教程中,您将学习如何创建第一个名为 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 命令,该命令运行应用程序。它将返回以下输出

请注意,您的二维码可能有所不同。
步骤 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! 的 Text 的 View。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() 函数中,我们定义了一个具有两个属性 container 和 text 的对象,它们的值是 JavaScript 对象,其作用类似于 CSS,定义了组件的外观和感觉。
container属性使用flex: 1、justifyContent: center和alignItems: 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 应用程序在手机上启动应用程序。