使用 Styled Components 和 TypeScript 设置 Expo
本指南将指导您使用 styled-components 和 TypeScript 设置 Expo 项目。该项目支持主题系统、暗黑模式和类型安全的 UI 组件,使其成为现代 React Native 应用程序的坚实基础。
代码
🚀 功能
🛠️ 快速入门
步骤 1:创建一个新的 Expo 项目
运行以下命令来初始化新的 Expo 项目:
npx create-expo-app styled-setup --template # Choose template: ➟ Blank (TypeScript)
第 2 步:安装依赖项
安装 styled-components 所需的依赖项:
# Install styled-components npm install styled-components # Install type definitions for styled-components npm install @types/styled-components-react-native --save-dev
📂 项目结构
使用以下结构组织您的项目:
├── app/ # Expo Router app directory │ ├── (tabs)/ # Tab navigation │ │ ├── index.tsx # First tab screen │ │ ├── two.tsx # Second tab screen │ │ └── _layout.tsx # Tab layout configuration │ ├── _layout.tsx # Root layout │ ├── modal.tsx # Modal screen │ └── +not-found.tsx # 404 screen ├── components/ │ ├── ui/ # UI components │ │ ├── button/ │ │ ├── container/ │ │ ├── text/ │ │ └── layout/ │ └── ExternalLink.tsx ├── themes/ # Theme configuration │ ├── colors.ts # Color definitions │ ├── sizes.ts # Size scales │ ├── spacing.ts # Spacing system │ ├── styles.ts # Common styles │ ├── theme.d.ts # Theme type definitions │ └── index.ts # Theme export └── hooks/ # Custom hooks └── useColors.ts # Theme colors hook
✨ 核心组件
按钮组件
Button 组件是一个灵活的、样式化的按钮,支持变体、大小和加载状态。
import Button from "@/components/ui/button"; // Usage ;
**道具:**
弹性布局
Flex 和 FlexItem 组件提供了受 CSS flexbox 启发的灵活布局系统。
import { Flex, FlexItem } from "@/components/ui/layout"; // Usage; Content
**道具:**
🎨主题系统
颜色
在 `themes/colors.ts` 中定义一致的调色板:
const colors = { primary: "#3b82f6", secondary: "#22c55e", success: "#16a34a", error: "#dc2626", warning: "#f59e0b", info: "#0ea5e9", // Additional colors... };
间距
在 `themes/spacing.ts` 中标准化间距:
const spacing = { padding: { xs: 4, sm: 8, md: 16, lg: 24, xl: 32, }, // Margin and gap definitions... };
排版
在 `themes/styles.ts` 中定义字体大小:
const fontSizes = { xs: 8, sm: 12, base: 14, md: 16, lg: 20, xl: 24, // Additional sizes... };
🌙 支持暗黑模式
该应用程序动态适应系统暗模式偏好:
function RootLayoutNav() { const colorScheme = useColorScheme(); return (); }
🛡️ 类型安全
主题类型
使用 `themes/theme.d.ts` 确保主题类型安全:
import "styled-components/native"; import theme from "."; export type AppTheme = typeof theme; declare module "styled-components/native" { export interface DefaultTheme extends AppTheme {} }
组件道具
定义按钮组件的 props:
type ButtonProps = { variant?: keyof typeof buttonVariants; size?: keyof typeof buttonSizes; shape?: keyof typeof buttonShapes; gap?: keyof typeof buttonGap; } & TouchableOpacityProps;
🔑 最佳实践
🏁 结论
本指南提供了使用样式化组件与 Expo 和 TypeScript 的全面设置。凭借强大的主题系统、暗黑模式支持和类型安全组件,此基础可确保可扩展且可维护的代码库。自定义和扩展此设置以满足您项目的独特要求。