React Native 入门教学:从零基础到开发第一个跨平台 App 详解指南

什么是 React Native?为什么要学习它?
React Native 是由 Facebook(现 Meta)开发的一个开源框架,它允许开发者使用 JavaScript 和 React 来构建真正的原生移动应用程序。与传统的混合应用开发框架(如 Cordova、Ionic)不同,React Native 不是运行在 WebView 中的网页应用,而是通过其桥接机制将 JavaScript 代码转换为原生 UI 组件。
React Native 的核心优势:
跨平台开发
:一套代码可以同时运行在 iOS 和 Android 平台上,大大减少了开发成本和时间
原生性能
:使用原生组件渲染,提供接近原生应用的性能和用户体验
热重载(Hot Reloading)
:开发时可以实时看到代码更改的效果,无需重新编译整个应用
庞大的生态系统
:基于 React 的庞大社区和丰富的第三方库
易于学习
:如果你已经熟悉 JavaScript 和 React,上手 React Native 会非常快
环境搭建:从零开始配置开发环境
系统要求
macOS 用户(开发 iOS):
macOS 10.15 或更高版本
Xcode 12 或更高版本
Node.js 14 或更高版本
Watchman(可选,但推荐)
Windows/Linux 用户(开发 Android):
Android Studio
Android SDK
Node.js 14 或更高版本
安装 Node.js 和 npm
首先,我们需要安装 Node.js,它是 React Native 开发的基础。访问
Node.js 官网
下载并安装 LTS 版本。
安装完成后,在终端中验证安装:
node –version
npm –version
安装 React Native CLI
React Native 提供了两种创建项目的方式:
React Native CLI
和
Expo
。对于初学者,我们推荐先使用 React Native CLI 来理解原生环境的配置。
# 安装 React Native CLI
npm install -g react-native-cli
iOS 开发环境配置(仅 macOS)
安装 Xcode
:从 Mac App Store 安装 Xcode
安装 CocoaPods
:在终端运行:
sudo gem install cocoapods
Android 开发环境配置
安装 Android Studio
:从
Android 官网
下载
配置环境变量
:
在
~/.bashrc
或
~/.zshrc
中添加:
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
创建 Android 虚拟设备(AVD)
:在 Android Studio 的 AVD Manager 中创建一个模拟器
创建你的第一个 React Native 项目
使用 React Native CLI 创建项目
# 创建一个名为 MyFirstApp 的项目
npx react-native init MyFirstApp

# 进入项目目录
cd MyFirstApp
项目结构详解
创建完成后,你的项目结构如下:
MyFirstApp/
├── android/ # Android 原生代码
├── ios/ # iOS 原生代码
├── src/ # 我们自己创建的源代码目录
├── App.js # 应用的入口文件
├── index.js # JavaScript 入口点
├── package.json # 项目依赖和配置
└── metro.config.js # Metro bundler 配置
运行你的第一个应用
在 iOS 模拟器上运行:
# 确保你在项目根目录
npx react-native run-ios
在 Android 模拟器上运行:
npx react-native run-android
如果一切正常,你应该能看到一个欢迎界面,显示 “Welcome to React Native!“。
React Native 核心概念详解
1. 组件(Components)
React Native 使用 React 组件模型。所有 UI 都是由组件构成的。最基本的组件包括:
View
:类似 HTML 中的 div,用于布局容器
Text
:用于显示文本
Image
:用于显示图片
TextInput
:文本输入框
ScrollView
:可滚动的容器
2. 样式(Styles)
React Native 使用 JavaScript 对象来定义样式,而不是 CSS。样式属性使用驼峰命名法(camelCase)。
import { StyleSheet } from ‘react-native’;

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: ‘#fff’,
alignItems: ‘center’,
justifyContent: ‘center’,
},
title: {
fontSize: 24,
fontWeight: ‘bold’,
color: ‘#333’,
marginBottom: 10,
},
button: {
backgroundColor: ‘#007AFF’,
paddingVertical: 12,
paddingHorizontal: 24,
borderRadius: 8,
},
});
3. Flexbox 布局
React Native 默认使用 Flexbox 布局,这与 CSS 中的 Flexbox 类似,但默认方向是
column
而不是
row
。
// 主轴对齐(垂直方向)
justifyContent: ‘flex-start’ | ‘center’ | ‘flex-end’ | ‘space-between’ | ‘space-around’

// 交叉轴对齐(水平方向)
alignItems: ‘stretch’ | ‘flex-start’ | ‘center’ | ‘flex-end’

// 主轴方向
flexDirection: ‘row’ | ‘column’ | ‘row-reverse’ | ‘column-reverse’
实战:开发一个完整的待办事项应用
让我们通过开发一个完整的待办事项应用来实践 React Native 的核心概念。
1. 项目初始化
首先,清理
App.js
文件,创建我们的应用结构:
// App.js
import React, { useState } from ‘react’;
import {
View,
Text,
TextInput,
TouchableOpacity,
StyleSheet,
ScrollView,
Alert,
} from ‘react-native’;

const App = () => {
// 状态管理
const [task, setTask] = useState(”);
const [tasks, setTasks] = useState([]);
const [editingId, setEditingId] = useState(null);

// 添加任务
const addTask = () => {
if (!task.trim()) {
Alert.alert(‘错误’, ‘任务不能为空’);
return;
}

if (editingId !== null) {
// 编辑模式
setTasks(tasks.map(t =>
t.id === editingId ? { …t, text: task } : t
));
setEditingId(null);
} else {
// 添加模式
const newTask = {
id: Date.now(),
text: task,
completed: false,
};
setTasks([…tasks, newTask]);
}

setTask(”);
};

// 删除任务
const deleteTask = (id) => {
Alert.alert(
‘确认删除’,
‘确定要删除这个任务吗?’,
[
{ text: ‘取消’, style: ‘cancel’ },
{
text: ‘删除’,
style: ‘destructive’,
onPress: () => setTasks(tasks.filter(t => t.id !== id))
},
]
);
};

// 切换完成状态
const toggleTask = (id) => {
setTasks(tasks.map(t =>
t.id === id ? { …t, completed: !t.completed } : t
));
};

// 开始编辑
const startEditing = (task) => {
setTask(task.text);
setEditingId(task.id);
};

return (

{/* 标题 */}
我的待办事项

{/* 输入区域 */}




{editingId !== null ? ‘更新’ : ‘添加’}


{/* 任务列表 */}

{tasks.length === 0 ? (
暂无任务,添加一个吧!
) : (
tasks.map((item) => (

toggleTask(item.id)}
>

{item.completed && ✓}


{item.text}


startEditing(item)}
>
编辑

deleteTask(item.id)}
>
删除



))
)}


);
};

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: ‘#f5f5f5’,
paddingTop: 60,
paddingHorizontal: 20,
},
title: {
fontSize: 28,
fontWeight: ‘bold’,
textAlign: ‘center’,
marginBottom: 20,
color: ‘#333’,
},
inputContainer: {
flexDirection: ‘row’,
marginBottom: 20,
},
input: {
flex: 1,
backgroundColor: ‘#fff’,
padding: 15,
borderRadius: 8,
fontSize: 16,
marginRight: 10,
borderWidth: 1,
borderColor: ‘#ddd’,
},
addButton: {
backgroundColor: ‘#007AFF’,
paddingVertical: 15,
paddingHorizontal: 20,
borderRadius: 8,
justifyContent: ‘center’,
},
addButtonText: {
color: ‘#fff’,
fontWeight: ‘bold’,
fontSize: 16,
},
taskList: {
flex: 1,
},
emptyText: {
textAlign: ‘center’,
color: ‘#999’,
fontSize: 16,
marginTop: 40,
},
taskItem: {
backgroundColor: ‘#fff’,
padding: 15,
borderRadius: 8,
marginBottom: 10,
flexDirection: ‘row’,
alignItems: ‘center’,
justifyContent: ‘space-between’,
shadowColor: ‘#000’,
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 2,
},
taskContent: {
flex: 1,
flexDirection: ‘row’,
alignItems: ‘center’,
},
checkbox: {
width: 24,
height: 24,
borderWidth: 2,
borderColor: ‘#007AFF’,
borderRadius: 4,
marginRight: 12,
justifyContent: ‘center’,
alignItems: ‘center’,
},
checkboxChecked: {
backgroundColor: ‘#007AFF’,
},
checkmark: {
color: ‘#fff’,
fontWeight: ‘bold’,
fontSize: 14,
},
taskText: {
fontSize: 16,
color: ‘#333’,
flex: 1,
},
taskTextCompleted: {
textDecorationLine: ‘line-through’,
color: ‘#999’,
},
taskActions: {
flexDirection: ‘row’,
},
editButton: {
backgroundColor: ‘#34C759’,
paddingVertical: 6,
paddingHorizontal: 12,
borderRadius: 4,
marginRight: 8,
},
deleteButton: {
backgroundColor: ‘#FF3B30’,
paddingVertical: 6,
paddingHorizontal: 12,
borderRadius: 4,
},
actionText: {
color: ‘#fff’,
fontSize: 12,
fontWeight: ‘bold’,
},
});

export default App;
2. 代码详解
让我们详细分析这个待办事项应用的代码:
状态管理
const [task, setTask] = useState(”);
const [tasks, setTasks] = useState([]);
const [editingId, setEditingId] = useState(null);
task
:当前输入框中的文本
tasks
:所有任务的数组
editingId
:当前正在编辑的任务ID(null表示添加模式)
核心函数
const addTask = () => {
if (!task.trim()) {
Alert.alert(‘错误’, ‘任务不能为空’);
return;
}

if (editingId !== null) {
// 编辑模式:更新现有任务
setTasks(tasks.map(t =>
t.id === editingId ? { …t, text: task } : t
));
setEditingId(null);
} else {
// 添加模式:创建新任务
const newTask = {
id: Date.now(),
text: task,
completed: false,
};
setTasks([…tasks, newTask]);
}

setTask(”);
};
这个函数处理了两种情况:
编辑模式
:当
editingId
不为 null 时,更新对应ID的任务文本
添加模式
:创建一个新任务对象并添加到数组中
UI 组件结构

我的待办事项





{tasks.map(…)}


3. 运行应用
现在运行你的应用:
# iOS
npx react-native run-ios

# Android
npx react-native run-android
你应该能看到一个功能完整的待办事项应用,支持添加、编辑、删除和标记完成。
进阶:导航(Navigation)
在实际应用中,我们通常需要多个页面。React Navigation 是最流行的导航库。
安装 React Navigation
# 安装核心包
npm install @react-navigation/native

# 安装依赖
npm install react-native-screens react-native-safe-area-context

# iOS 额外步骤
cd ios && pod install && cd ..

# 安装堆栈导航器
npm install @react-navigation/stack
npm install react-native-gesture-handler
创建多页面应用
// App.js
import React from ‘react’;
import { NavigationContainer } from ‘@react-navigation/native’;
import { createStackNavigator } from ‘@react-navigation/stack’;
import HomeScreen from ‘./src/screens/HomeScreen’;
import DetailScreen from ‘./src/screens/DetailScreen’;

const Stack = createStackNavigator();

const App = () => {
return (






);
};

export default App;
// src/screens/HomeScreen.js
import React from ‘react’;
import { View, Text, Button, StyleSheet } from ‘react-native’;

const HomeScreen = ({ navigation }) => {
return (

首页