关于 react-native-patterns
react-native-patterns 是一项用于构建 React Native 和 Expo 移动应用的实践技能,涵盖项目初始化、导航、平台代码、样式、性能和常用库。
主要功能
- 01Expo 与裸 React Native 项目初始化
- 02基于文件或导航库的路由
- 03iOS 与 Android 专属代码
- 04样式与常用库建议
- 05列表和组件性能优化
- 06表单、安全区域与更新提示
适用场景
- 01启动新的 Expo 移动应用
- 02为 iOS 和 Android 处理界面差异
- 03改善长列表渲染性能
- 04规划导航、数据获取与表单库
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ revitalb-port/ skills-registry-demo --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