关于 react-native-patterns
面向 React Native 和 Expo 移动应用开发的模式指南,涵盖项目搭建、导航、平台差异、样式和性能实践。
主要功能
- 01Expo 与原生项目搭建
- 02导航方案示例
- 03平台专属代码组织
- 04样式与性能建议
- 05常见库选型参考
适用场景
- 01启动 React Native 或 Expo 项目
- 02设计跨 iOS 与 Android 的界面
- 03优化长列表和组件渲染
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ spencerpauly/ awesome-cursor-skills --skill react-native-patterns安装后在 Claude Code 中输入/react-native-patterns确认已加载。
详细介绍
React Native 模式
使用 React Native 和 Expo 构建可用于生产环境的移动应用。
项目设置
Expo(大多数项目的推荐选择):
npx create-expo-app@latest my-app
cd my-app
npx expo start
Bare React Native(需要完全控制原生功能时):
npx @react-native-community/cli init MyApp
除非你需要 Expo 不支持的自定义原生模块,否则请使用 Expo。
导航
使用 expo-router(基于文件的路由)或 @react-navigation/native:
app/
├── _layout.tsx # Root layout (tabs, stack, drawer)
├── index.tsx # Home screen
├── (tabs)/
│ ├── _layout.tsx # Tab navigator
│ ├── home.tsx
│ ├── profile.tsx
│ └── settings.tsx
└── [id].tsx # Dynamic route
平台特定代码
import { Platform } from 'react-native';
const styles = StyleSheet.create({
shadow: Platform.select({
ios: { shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1 },
android: { elevation: 4 },
}),
});
如需处理更大的差异,请使用平台特定文件:
Component.ios.tsxComponent.android.tsx
样式
使用 StyleSheet.create 提高性能(样式只会发送到原生端一次):
const styles = StyleSheet.create({
container: { flex: 1, padding: 16 },
title: { fontSize: 24, fontWeight: '700' },
});
如需类似 Tailwind 的体验,请使用 nativewind:
<View className="flex-1 p-4">
<Text className="text-2xl font-bold">Hello</Text>
</View>
性能
长列表使用 FlatList 而非 ScrollView:
<FlatList
data={items}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <ItemRow item={item} />}
initialNumToRender={10}
maxToRenderPerBatch={5}
windowSize={5}
/>
对开销较大的组件进行记忆化处理:
const ItemRow = React.memo(({ item }: { item: Item }) => (
<View><Text>{item.name}</Text></View>
));
避免:
- 内联样式(每次渲染都会创建新对象)
- 在
renderItem中使用匿名函数 - 使用未经缓存的大型图片(
expo-image会处理缓存)
常用库
| 需求 | 库 |
|---|---|
| 导航 | expo-router 或 @react-navigation/native |
| 状态 | zustand、jotai 或 React context |
| 数据获取 | @tanstack/react-query |
| 图片 | expo-image |
| 图标 | @expo/vector-icons |
| 存储 | expo-secure-store(敏感数据)、@react-native-async-storage/async-storage(常规数据) |
| 动画 | react-native-reanimated |
| 手势 | react-native-gesture-handler |
| 表单 | react-hook-form + zod |
提示
- 从一开始就同时在 iOS 和 Android 上测试,不要等到最后
- 在 Expo 中使用
expo-dev-client支持自定义原生模块 - 使用
react-native-safe-area-context处理安全区域 - 务必为表单处理键盘避让(
KeyboardAvoidingView) - 在生产环境中使用
expo-updates进行 OTA 更新
评论
支持 Markdown