React Native 在移动开发中:概念、核心原理及工作方式

作者: IT Sectr 发布日期: 2026-07-12 阅读时间: 10 分钟
React Native 是 Meta 推出的跨平台框架,用于开发原生移动应用。根据 React Native Docs (2025),RN 被用于 Instagram、Facebook、Shopify 和 Pinterest 等应用中。理解 JSX、Hooks、FlatList 和 StyleSheet 是 React Native 开发的基础。

要点

  • JSX — UI 语法。表达式放在 {} 中。没有 HTML 标签 — 只有 RN 组件(View、Text、Image)。
  • Hooks:useState(状态)、useEffect(副作用)、useRef(引用)、useCallback(函数记忆化)、useMemo(值记忆化)。
  • FlatList — 虚拟化列表。优化:keyExtractor、getItemLayout、windowSize、React.memo。
  • StyleSheet — camelCase 样式(backgroundColor)。默认使用 Flexbox。无 CSS 层叠。
  • Metro Bundler — JS 打包。Hermes — 快速 JS 引擎(从 RN 0.70+ 开始默认)。

基础(JSX、Functional Component、Hooks)

JSX(JavaScript XML) — JavaScript 的语法扩展,用于描述 UI。看起来像 HTML,但通过 React.createElement() 工作。JSX 表达式:{variable}{condition && <View />}{array.map()}Functional Component — 一个返回 JSX 的函数。接收 props 作为参数。React 的现代标准(在 React 16.8 之前使用的是 Class Components)。Hooks — 从 Functional Component 访问状态和生命周期的方法。Hooks 规则:只在顶层使用,只在 Functional Components 中使用。

Hooks 参考

useState — 本地状态。useEffect — 副作用。useContext — 访问 Context。useRef — 可变引用。useCallback — 函数记忆化。useMemo — 值记忆化。Custom Hooks — 可复用逻辑:function useDebounce(value, delay)。

javascript
// 在 React Native 中使用 hooks 的 Functional Component
import React, { useState, useEffect, useCallback } from 'react';
import {
  View, Text, FlatList,
  ActivityIndicator, SafeAreaView
} from 'react-native';

const DATA = Array.from({ length: 100 }, (_, i) => ({
  id: String(i),
  title: `Item ${i + 1}`,
}));

const Item = React.memo(({ title }) => (
  <View>
    <Text>{title}</Text>
  </View>
));

export default function App() {
  const [refreshing, setRefreshing] = useState(false);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    setTimeout(() => setRefreshing(false), 2000);
  }, []);

  return (
    <SafeAreaView>
      <FlatList
        data={DATA}
        renderItem={({ item }) => <Item title={item.title} />}
        keyExtractor={item => item.id}
        refreshing={refreshing}
        onRefresh={onRefresh}
      />
    </SafeAreaView>
  );
}

Hooks(useState、useEffect、useRef、useCallback、useMemo)

useState — 返回 [value, setValue]。setValue — 替换(不合并,像 Class 中的 setState)。对于对象:setUser(prev => ({ ...prev, name: 'New' }))。useEffect — 在渲染后执行。依赖数组:[] — 一次(挂载时),[dep] — 当 dep 改变时,undefined — 每次渲染。清理函数 — return () => {}。useContext — const value = useContext(MyContext)。需要在树中更高的位置有 Context.Provider。

useRef — 可变对象,在渲染之间保持值不变。.current — 变更。用于:访问原生元素(ref={inputRef})、存储先前的值、定时器。useCallback — 返回记忆化的函数。const handlePress = useCallback(() => {}, [dep])。useMemo — 返回记忆化的值。const sorted = useMemo(() => data.sort(), [data])。对于昂贵的计算使用 useMemo。

Hook 用途 返回
useState本地状态[value, setValue]
useEffect副作用(fetch、订阅)void(清理可选)
useContext访问 Contextcontext value
useRef渲染之间的可变引用{ current: T }
useCallback函数记忆化记忆化的 fn
useMemo值记忆化记忆化的值
useReducer复杂状态(归约器)[state, dispatch]

useState — 用于简单状态。useEffect — 用于 API 调用和订阅。useCallback/useMemo — 用于优化。IT Sectr 建议不要记忆化所有内容 — 只有在存在实际性能问题时才使用。

Custom Hooks

Custom Hook — 使用内置 hooks 的函数。名称以 use* 开头。示例:useDebounce、useNetworkStatus、useAppState、useKeyboard。Custom Hooks 是在 React Native 中复用逻辑的主要方式。IT Sectr 建议将业务逻辑提取到 Custom Hooks 中,并保持组件简洁(仅 JSX + 样式)。

组件(View、Text、FlatList、ScrollView、SafeAreaView)

View — 基本容器(类似于 div)。Text — 文本(唯一的文本组件)。TextInput — 文本输入。ScrollView — 可滚动的容器。FlatList — 用于大数据集的虚拟化列表。SectionList — 带分组的 FlatList。SafeAreaView — 自动从 Safe Area(刘海、状态栏)添加间距。Pressable — TouchableOpacity 的现代替代品。useColorScheme — 深色/浅色主题检测。

FlatList 优化

FlatList — 虚拟化:仅渲染可见元素 + windowSize。优化:1)keyExtractor — 唯一键,2)getItemLayout — 固定高度(跳过 onLayout 测量),3)renderItem 使用 React.memo,4)maxToRenderPerBatch(默认 10),5)windowSize(默认 21),6)removeClippedSubviews,7)initialNumToRender。

React Navigation — 标准导航栈。NativeStackNavigator — 原生动画(push/pop)。TabNavigator — 底部标签页。DrawerNavigator — 侧边菜单。NavigationContainer — 导航的根组件。Deep linking — 外部链接的链接配置。认证流程 — 条件导航:isAuth ? AppStack : AuthStack。IT Sectr 建议主屏幕使用 NativeStackNavigator,第一级导航使用 TabNavigator。

样式(StyleSheet)

StyleSheet.create() — 创建样式。所有属性使用 camelCase:backgroundColor、fontSize、marginTop。Flexbox — 默认布局模型(flexDirection: 'column')。没有 CSS 层叠、没有继承、没有选择器。内联样式 — 可用但不推荐。StyleSheet.compose() — 组合样式。Platform.select — 平台特定样式:Platform.OS === 'ios' ? styles.ios : styles.android。SafeAreaView — 管理安全区域插入。

Styled Components 和 CSS-in-JS

Styled Components — React Native 中 CSS-in-JS 的库。Restyle — 主题化 + 响应式样式。NativeWind — React Native 的 Tailwind CSS。Unistyles — 原子 CSS 的快速样式。深色模式 — useColorScheme + 动态样式。IT Sectr 推荐使用 StyleSheet.create 以保持简单,对于有设计系统的项目推荐使用 NativeWind。

动画(Animated API)

Animated API — 声明式动画。Animated.Value — 动画值。Animated.timing — 简单动画。Animated.spring — 弹簧动画。Animated.View — 可动画化的 View。useNativeDriver — 在原生线程上执行动画(支持 transform、opacity)。Animated.loop — 循环动画。LayoutAnimation — 布局更改时自动动画。reanimated 2/3(库) — 更高性能的替代方案。Metro Bundler — JavaScript 打包器。将 JS + 资源打包到一个 bundle 中。支持 Fast Refresh(热重载)。Hermes — 针对移动设备优化的 JS 引擎:快速启动、更少内存。从 RN 0.70+ 开始默认。

Gesture Handler 和动画

React Native Gesture Handler — 原生手势处理。PanGestureHandler、PinchGestureHandler、TapGestureHandler。Gesture(RNGH 2.x) — 声明式手势 API。Reanimated + Gesture Handler — 结合使用可实现 60fps 手势动画。react-native-skia — 用于复杂 2D 图形的 GPU 渲染。IT Sectr 建议使用 Reanimated 3 实现所有性能优于 Animated API 的动画。

网络(fetch、AsyncStorage、API)

fetch — 内置 HTTP 客户端。支持 GET、POST、headers、body。Axios — 带有拦截器的流行库。AsyncStorage — 键值存储(类似于 UserDefaults)。MMKV — WeChat 提供的 AsyncStorage 快速替代品。react-native-keychain — 安全的令牌存储。React Query(TanStack Query) — 服务器状态管理:缓存、重新验证、分页。IT Sectr 建议 API 请求使用 React Query,本地存储使用 MMKV。

javascript
import AsyncStorage from '@react-native-async-storage/async-storage';

const storeToken = async (token) => {
  try {
    await AsyncStorage.setItem('@auth_token', token);
  } catch (e) {
    console.error('Storage error:', e);
  }
};

const getToken = async () => {
  try {
    return await AsyncStorage.getItem('@auth_token');
  } catch (e) {
    return null;
  }
};

Native Modules 和 Turbo Modules

Native Module — JS 和原生代码之间的桥梁(Android 使用 Java/Kotlin,iOS 使用 ObjC/Swift)。允许从 JS 调用原生 API。Turbo Modules(新架构) — 替代旧的 Native Modules。同步调用、通过 Codegen 进行类型化、更少的开销。Fabric Renderer — 具有同步布局的新渲染器。JSI(JavaScript Interface) — JS 直接访问原生对象,无需桥梁。IT Sectr 建议新项目使用 Turbo Modules,现有项目使用 Native Modules。

kotlin
// Android 原生模块(Kotlin)
class CalendarModule(reactContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactContext) {

    override fun getName() = "CalendarModule"

    @ReactMethod
    fun createCalendarEvent(name: String, location: String) {
        val intent = Intent(Intent.ACTION_EDIT).apply {
            type = "vnd.android.cursor.item/event"
            putExtra(Events.TITLE, name)
            putExtra(Events.EVENT_LOCATION, location)
        }
        reactContext.startActivity(intent)
    }
}

测试(Jest、React Native Testing Library)

Jest — 标准测试运行器。describe/it/expect。React Native Testing Library — 组件测试。render、fireEvent、waitFor。screen.getByText、getByTestId — 查找。userEvent — 操作模拟。Snapshot 测试 — toMatchSnapshot()。MSW(Mock Service Worker) — API 模拟。Detox — RN 的 E2E 测试(灰盒、原生)。IT Sectr 建议组件测试使用 React Native Testing Library,端到端场景使用 Detox。

CodePush(App Center) — 无需发布到 App Store/Google Play 即可对 JS bundle 进行 OTA 更新。用于:热修复、A/B 测试、内容更改。限制:无法更改原生代码。替代方案:EAS Update(Expo)、react-native-update。IT Sectr 建议紧急修复使用 CodePush,Expo 项目使用 EAS Update。

Expo — React Native 的框架。托管工作流 — 所有配置通过 app.json 进行。开发构建 — 无需 eject 即可使用自定义原生模块。Expo SDK — 内置模块:相机、生物识别、通知。EAS Build — 云端构建。Expo Router — 基于文件的路由(类似于 Next.js)。IT Sectr 建议新项目使用 Expo,深度原生定制的项目使用 bare RN。

常见问题

React Native 中的 JSX 是什么?

JSX — 用于 UI 的 JavaScript 扩展。表达式放在 {} 中。没有 HTML 标签——只有 RN 组件(View、Text)。

hooks 之间有什么区别?

useState — 状态。useEffect — 副作用。useRef — 引用。useCallback — 函数记忆化。useMemo — 值记忆化。

如何优化 FlatList?

FlatList — keyExtractor、getItemLayout、React.memo、windowSize、maxToRenderPerBatch、removeClippedSubviews。

StyleSheet 是什么?

StyleSheet.create() — camelCase 样式(backgroundColor、fontSize)。默认使用 Flexbox。无 CSS 层叠。

Metro Bundler 和 Hermes 是什么?

Metro — JS 打包器。Hermes — 快速 JS 引擎。两者都来自 Meta。Hermes — 从 RN 0.70+ 开始默认。

总结

  • JSX — UI 语法。Functional Component + Hooks — 现代 React Native 标准。
  • Hooks:useState(状态)、useEffect(副作用)、useCallback/useMemo(记忆化)。
  • FlatList — 最优列表。keyExtractor + getItemLayout + React.memo — 基本优化。
  • StyleSheet — camelCase + flexbox。SafeAreaView — 现代设备必须使用。
  • Animated API — 通过 useNativeDriver 实现原生动画。reanimated — 用于复杂场景。
  • Pressable — TouchableOpacity 的现代替代品。SectionList — 用于分组列表。
  • Metro + Hermes — 标准 RN 构建栈。Hermes — 快速启动、更少内存。

我们将开发一款交钥匙移动应用程序

IT Sectr自2017年以来为初创企业和企业打造iOS和Android应用程序。我们将为您提供咨询并提出最佳解决方案。

讨论项目