ReactNative 基础
概述
React Native 是 Facebook 开源的跨平台移动应用框架,使用 React 语法开发 iOS 和 Android 应用。
核心特点:
- Learn once, write anywhere — 一套代码,iOS 和 Android 双端运行
- 原生组件 — 编译为原生 UI 组件,不是 WebView
- 热更新 — Metro bundler 支持快速刷新
- 原生能力 — 可调用原生模块(相机、GPS、蓝牙等)
Expo vs React Native CLI
| 特性 | Expo | React Native CLI |
|---|---|---|
| 上手难度 | 低,零配置 | 高,需配置原生环境 |
| 原生模块 | 内置常用模块 | 需手动链接 |
| 构建服务 | EAS Build(云端) | 本地 Xcode / Android Studio |
| 自定义原生代码 | 需 eject 或开发插件 | 完全控制 |
| 适合场景 | 中小型应用、快速原型 | 大型应用、需深度原生定制 |
推荐:新项目优先选择 Expo,需要原生自定义时使用 CLI。
环境搭建
Expo
bash
npm install -g expo-cli
expo init my-app
cd my-app
npx expo startnpm install -g expo-cli
expo init my-app
cd my-app
npx expo startReact Native CLI
bash
# 安装 React Native CLI
npx @react-native-community/cli init my-app
# 运行(需提前打开模拟器)
npx react-native run-ios
npx react-native run-android# 安装 React Native CLI
npx @react-native-community/cli init my-app
# 运行(需提前打开模拟器)
npx react-native run-ios
npx react-native run-androidAndroid 环境要求:JDK 17+、Android Studio、Android SDK、环境变量 ANDROID_HOME。
iOS 环境要求:macOS、Xcode、CocoaPods。
目录结构
my-app/
android/ # Android 原生项目
ios/ # iOS 原生项目
src/
components/ # UI 组件
screens/ # 页面
navigation/ # 导航配置
utils/ # 工具函数
assets/ # 图片、字体等资源
App.tsx # 入口文件
package.jsonmy-app/
android/ # Android 原生项目
ios/ # iOS 原生项目
src/
components/ # UI 组件
screens/ # 页面
navigation/ # 导航配置
utils/ # 工具函数
assets/ # 图片、字体等资源
App.tsx # 入口文件
package.json入口文件
tsx
import React from 'react'
import { View, Text, StyleSheet } from 'react-native'
export default function App() {
return (
<View style={styles.container}>
<Text>Hello React Native</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
})import React from 'react'
import { View, Text, StyleSheet } from 'react-native'
export default function App() {
return (
<View style={styles.container}>
<Text>Hello React Native</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
})类组件写法
tsx
import React from 'react'
import { View, Text } from 'react-native'
export default class App extends React.Component {
render() {
return <View></View>
}
}import React from 'react'
import { View, Text } from 'react-native'
export default class App extends React.Component {
render() {
return <View></View>
}
}常用开发工具
- Metro Bundler — React Native 的 JavaScript 打包器
- React DevTools — 调试 React 组件
- Flipper — 原生调试工具(网络、数据库、布局)
- Expo Go — Expo 项目的真机调试 App
Cao Note