React Native第一个应用 #

创建项目 #

使用 React Native CLI #

打开终端,运行以下命令创建新项目:

bash
npx react-native@latest init MyFirstApp

使用 TypeScript 模板(推荐) #

bash
npx react-native@latest init MyFirstApp --template react-native-template-typescript

CLI 选项 #

创建项目时可以指定更多选项:

bash
npx react-native@latest init MyFirstApp \
  --template react-native-template-typescript \
  --directory my-app \
  --skip-install
选项 说明
–template 指定项目模板
–directory 指定项目目录名
–skip-install 跳过依赖安装
–title 设置应用显示名称
–pm 指定包管理器 (npm/yarn)

项目结构 #

创建完成后,项目目录结构如下:

text
MyFirstApp/
├── android/                    # Android 原生项目
│   ├── app/
│   ├── gradle/
│   ├── build.gradle
│   └── settings.gradle
├── ios/                        # iOS 原生项目
│   ├── MyFirstApp/
│   ├── MyFirstApp.xcodeproj/
│   ├── MyFirstApp.xcworkspace/
│   └── Podfile
├── node_modules/               # 依赖包
├── .gitignore
├── .eslintrc.js               # ESLint 配置
├── .prettierrc.js             # Prettier 配置
├── App.tsx                    # 应用入口组件
├── app.json                   # 应用配置
├── babel.config.js            # Babel 配置
├── index.js                   # 应用注册入口
├── metro.config.js            # Metro 配置
├── package.json               # 项目配置
└── tsconfig.json              # TypeScript 配置

核心文件说明 #

App.tsx #

应用的主入口组件:

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

function App(): React.JSX.Element {
  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content}>
        <Text style={styles.title}>Hello, React Native!</Text>
        <Text style={styles.subtitle}>Welcome to your first app</Text>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  content: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
  },
  subtitle: {
    fontSize: 16,
    color: '#666',
    marginTop: 8,
  },
});

export default App;

package.json #

项目配置和依赖:

json
{
  "name": "MyFirstApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "lint": "eslint .",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "react": "18.2.0",
    "react-native": "0.73.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@babel/preset-env": "^7.20.0",
    "@types/react": "^18.2.0",
    "typescript": "^5.0.0"
  }
}

运行应用 #

启动 Metro Bundler #

Metro 是 React Native 的 JavaScript 打包工具:

bash
cd MyFirstApp
npx react-native start

或者使用 npm 脚本:

bash
npm start

运行 iOS 应用 #

在新终端窗口中:

bash
npx react-native run-ios

指定模拟器:

bash
npx react-native run-ios --simulator="iPhone 15 Pro"

查看可用模拟器:

bash
xcrun simctl list devices

运行 Android 应用 #

确保 Android 模拟器正在运行,然后:

bash
npx react-native run-android

指定设备:

bash
npx react-native run-android --deviceId=emulator-5554

查看已连接设备:

bash
adb devices

开发体验 #

热重载 #

React Native 支持热重载,修改代码后应用会自动更新:

  1. 在模拟器中按 Cmd + D (iOS) 或 Cmd + M (Android)
  2. 选择 “Enable Hot Reloading”

快速刷新 #

快速刷新是热重载的改进版本:

  • 保留组件状态
  • 只更新修改的部分
  • 错误时自动回退

开发者菜单 #

在模拟器中打开开发者菜单:

  • iOSCmd + D
  • AndroidCmd + M 或摇晃设备

菜单选项:

选项 说明
Reload 重新加载应用
Debug JS Remotely 远程调试
Enable Hot Reloading 启用热重载
Show Perf Monitor 显示性能监视器
Show Element Inspector 显示元素检查器

修改应用 #

让我们修改 App.tsx,添加一些交互功能:

tsx
import React, {useState} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Alert,
} from 'react-native';

function App(): React.JSX.Element {
  const [count, setCount] = useState(0);

  const handlePress = () => {
    setCount(count + 1);
  };

  const handleReset = () => {
    Alert.alert('确认', '确定要重置计数吗?', [
      {text: '取消', style: 'cancel'},
      {
        text: '确定',
        onPress: () => setCount(0),
      },
    ]);
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content}>
        <Text style={styles.title}>计数器应用</Text>
        <Text style={styles.count}>{count}</Text>
        
        <TouchableOpacity style={styles.button} onPress={handlePress}>
          <Text style={styles.buttonText}>点击 +1</Text>
        </TouchableOpacity>
        
        <TouchableOpacity
          style={[styles.button, styles.resetButton]}
          onPress={handleReset}>
          <Text style={styles.buttonText}>重置</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  content: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 30,
  },
  count: {
    fontSize: 72,
    fontWeight: 'bold',
    color: '#007AFF',
    marginBottom: 40,
  },
  button: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 30,
    paddingVertical: 15,
    borderRadius: 8,
    marginBottom: 15,
    minWidth: 150,
    alignItems: 'center',
  },
  resetButton: {
    backgroundColor: '#FF3B30',
  },
  buttonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
});

export default App;

保存后,应用会自动刷新显示新的计数器界面。

调试应用 #

使用 console.log #

在代码中添加日志:

tsx
console.log('当前计数:', count);
console.warn('这是一个警告');
console.error('这是一个错误');

在 Metro 终端中查看输出。

使用 React Native Debugger #

  1. 安装 React Native Debugger
  2. 在开发者菜单中选择 “Debug JS Remotely”
  3. Debugger 会自动打开

使用 Flipper #

Flipper 提供了更强大的调试功能:

  • 网络请求检查
  • 布局检查
  • 数据库查看
  • 性能分析

真机调试 #

iOS 真机调试 #

  1. 用数据线连接 iPhone 到 Mac
  2. 在 Xcode 中选择你的设备
  3. 首次运行需要信任开发者证书

配置开发者团队:

  1. 打开 ios/MyFirstApp.xcworkspace
  2. 选择项目 → Signing & Capabilities
  3. 选择你的 Team

Android 真机调试 #

  1. 开启开发者选项和 USB 调试
  2. 用数据线连接设备
  3. 运行 adb devices 确认连接
  4. 运行 npx react-native run-android

常见问题 #

Metro bundler 无法启动 #

清理缓存:

bash
npx react-native start --reset-cache

iOS 构建失败 #

bash
cd ios
pod install
cd ..
npx react-native run-ios

Android 构建失败 #

清理 Gradle 缓存:

bash
cd android
./gradlew clean
cd ..
npx react-native run-android

无法连接到开发服务器 #

确保设备和电脑在同一网络,然后:

bash
adb reverse tcp:8081 tcp:8081

总结 #

恭喜你成功创建并运行了第一个 React Native 应用!你已经了解了:

  • 如何创建 React Native 项目
  • 项目的基本结构
  • 如何运行和调试应用
  • 如何使用热重载提高开发效率

接下来,让我们深入了解 React Native 的核心概念。

继续学习 核心概念,理解 React Native 的工作原理。

最后更新:2026-03-28