前端开发指南
目的
基于 React 19 的现代 Next.js 15 开发综合指南,重点介绍 Server Components、Client Components、App Router 模式、Shadcn/ui 组件、合理的文件组织和性能优化。
何时使用此技能
- 创建新的组件或页面
- 构建新功能
- 获取数据(Server Components、Server Actions)
- 使用 Next.js App Router 设置路由
- 使用 Tailwind CSS 和 Shadcn/ui 设计组件样式
- 性能优化
- 组织前端代码
- TypeScript 最佳实践
快速开始
新建组件检查清单
创建组件?请遵循此清单:
- 确定 Server Component 还是 Client Component(默认:Server Component)
- 仅在需要时添加
"use client"指令(交互性、hooks、浏览器 API) - 使用带有显式 prop 类型的 TypeScript
- 从
@/components/ui导入 Shadcn/ui 组件 - 使用 Tailwind CSS 类进行样式设计
- 使用导入别名:
@/components、@/lib、@/hooks - 使用
cn()工具函数处理条件类 - 底部使用默认导出
- 尽可能使用 Server Components 进行数据获取
新建页面检查清单
创建页面?请设置此结构:
- 为路由创建
app/{route-name}/page.tsx - 默认使用 Server Component
- 直接在 Server Component 中获取数据
- 为页面特定组件创建
components/目录 - 使用
loading.tsx处理加载状态 - 使用
error.tsx处理错误边界 - 导出 metadata 用于 SEO
导入别名快速参考
| 别名 | 解析路径 | 示例 |
|---|---|---|
@/ | 项目根目录 | import { cn } from '@/lib/utils' |
@/components | components/ | import { Button } from '@/components/ui/button' |
@/lib | lib/ | import { cn } from '@/lib/utils' |
@/hooks | hooks/ | import { useMobile } from '@/hooks/use-mobile' |
@/app | app/ | import { Metadata } from 'next' |
定义于:tsconfig.json 路径配置
常见导入速查表
// Next.js
import { Metadata } from 'next'
import { Suspense } from 'react'
import { notFound, redirect } from 'next/navigation'
// React (仅 Client Components)
;('use client')
import { useState, useCallback, useMemo } from 'react'
// Shadcn/ui Components
import { Button } from '@/components/ui/button'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
// Utilities
import { cn } from '@/lib/utils'
// Hooks (仅 Client Components)
import { useMobile } from '@/hooks/use-mobile'
// Types
import type { ComponentProps } from 'react'
主题指南
🎨 组件模式
Server Components 与 Client Components:
- Server Components(默认):无
"use client",可直接获取数据,打包体积更小 - Client Components:添加
"use client"以支持交互性、hooks、浏览器 API
关键概念:
- 默认使用 Server Components
- 仅在必要时使用 Client Components
- 使用 Shadcn/ui 组件(它们本身就是 Client Components)
- 组件结构:Props → 数据获取 → 渲染 → 导出
Server Component 示例:
// app/features/posts/components/PostList.tsx
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
interface PostListProps {
posts: Post[]
}
export function PostList({ posts }: PostListProps) {
return (
<div className='grid gap-4'>
{posts.map((post) => (
<Card key={post.id}>
<CardHeader>
<CardTitle>{post.title}</CardTitle>
</CardHeader>
<CardContent>{post.content}</CardContent>
</Card>
))}
</div>
)
}
Client Component 示例:
// app/features/posts/components/PostForm.tsx
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
export function PostForm() {
const [title, setTitle] = useState('')
return (
<form>
<Input value={title} onChange={(e) => setTitle(e.target.value)} />
<Button type='submit'>Submit</Button>
</form>
)
}
📊 数据获取
首要模式:Server Components
- 直接在 Server Components 中获取数据
- 在 Server Components 中使用
async/await - 无需
useEffect或数据获取库 - 自动请求去重
Server Actions:
- 用于变更操作(表单、更新)
- 创建
app/actions/目录 - 使用
"use server"指令标记
带数据获取的 Server Component 示例:
// app/posts/page.tsx
import { PostList } from '@/components/PostList'
async function getPosts() {
const res = await fetch('https://api.example.com/posts', {
cache: 'no-store', // 或 'force-cache', 'revalidate'
})
return res.json()
}
export default async function PostsPage() {
const posts = await getPosts()
return <PostList posts={posts} />
}
Server Action 示例:
// app/actions/posts.ts
'use server'
export async function createPost(formData: FormData) {
const title = formData.get('title')
// ... 验证和创建逻辑
redirect('/posts')
}
📁 文件组织
App Router 结构:
app/
(routes)/
page.tsx # 路由页面
layout.tsx # 路由布局
loading.tsx # 加载 UI
error.tsx # 错误 UI
components/ # 共享组件
ui/ # Shadcn/ui 组件
features/ # 功能特定代码
posts/
components/ # 功能组件
actions/ # Server Actions
types/ # TypeScript 类型
lib/
utils.ts # 工具函数 (cn, 等)
hooks/
use-mobile.ts # 自定义 hooks (仅 Client)
功能组织:
app/features/{feature}/:功能特定页面/路由components/:真正可复用的组件components/ui/:Shadcn/ui 组件(不要直接修改)
🎨 样式
Tailwind CSS + Shadcn/ui:
- 使用 Tailwind 工具类
- 使用
cn()工具函数处理条件类 - Shadcn/ui 组件使用 CSS 变量进行主题定制
- 在
app/globals.css中自定义主题
样式模式:
import { cn } from '@/lib/utils'
interface ButtonProps {
variant?: 'primary' | 'secondary'
className?: string
}
export function Button({ variant = 'primary', className }: ButtonProps) {
return (
<button
className={cn(
'rounded-md px-4 py-2',
variant === 'primary' && 'bg-primary text-primary-foreground',
variant === 'secondary' && 'bg-secondary text-secondary-foreground',
className,
)}
>
Click me
</button>
)
}
Shadcn/ui 组件:
- 从
@/components/ui/{component-name}导入 - 组件已预置样式且可访问
- 通过
classNameprop 或 CSS 变量进行自定义
🛣️ 路由
Next.js App Router - 基于文件:
- 目录:
app/{route-name}/page.tsx - 嵌套路由:
app/{parent}/{child}/page.tsx - 动态路由:
app/posts/[id]/page.tsx - 路由组:
app/(marketing)/about/page.tsx
路由示例:
// app/posts/page.tsx
import { Metadata } from 'next'
import { PostList } from '@/components/PostList'
export const metadata: Metadata = {
title: 'Posts',
description: 'List of all posts',
}
export default async function PostsPage() {
const posts = await getPosts()
return (
<div className='container mx-auto py-8'>
<h1 className='text-3xl font-bold mb-6'>Posts</h1>
<PostList posts={posts} />
</div>
)
}
动态路由:
// app/posts/[id]/page.tsx
interface PostPageProps {
params: Promise<{ id: string }>
}
export default async function PostPage({ params }: PostPageProps) {
const { id } = await params
const post = await getPost(id)
if (!post) {
notFound()
}
return <PostDetail post={post} />
}
⏳ 加载与错误状态
加载状态:
- 在路由目录中创建
loading.tsx - 自动将页面包裹在 Suspense 中
- 用于路由级别的加载
错误边界:
- 在路由目录中创建
error.tsx - 自动捕获路由中的错误
- 可重置错误状态
加载 UI 示例:
// app/posts/loading.tsx
export default function Loading() {
return (
<div className='flex items-center justify-center min-h-screen'>
<div className='animate-spin rounded-full h-8 w-8 border-b-2 border-primary' />
</div>
)
}
错误 UI 示例:
// app/posts/error.tsx
'use client'
import { useEffect } from 'react'
import { Button } from '@/components/ui/button'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
console.error(error)
}, [error])
return (
<div className='flex flex-col items-center justify-center min-h-screen'>
<h2 className='text-2xl font-bold mb-4'>Something went wrong!</h2>
<Button onClick={reset}>Try again</Button>
</div>
)
}
⚡ 性能
优化模式:
- 使用 Server Components(打包体积更小)
- 使用
next/image处理图片 - 使用
next/font处理字体 - 尽可能懒加载 Client Components
- 在 Client Components 中使用
useMemo和useCallback - 使用 Suspense 边界流式传输数据
图片优化:
import Image from 'next/image'
export function Avatar({ src, alt }: { src: string; alt: string }) {
return (
<Image
src={src}
alt={alt}
width={40}
height={40}
className='rounded-full'
/>
)
}
使用 Suspense 流式传输:
import { Suspense } from 'react'
import { PostList } from '@/components/PostList'
import { Loading } from '@/components/Loading'
export default function Page() {
return (
<div>
<Suspense fallback={<Loading />}>
<PostList />
</Suspense>
</div>
)
}
📘 TypeScript
标准:
- 启用严格模式
- 无
any类型 - 函数显式返回类型
- 类型导入:
import type { Post } from '@/types/post' - 组件 prop 接口附带 JSDoc
示例:
import type { ComponentProps } from 'react'
import { Button } from '@/components/ui/button'
/**
* 带有加载状态的自定义按钮组件
*/
interface CustomButtonProps extends ComponentProps<typeof Button> {
isLoading?: boolean
}
export function CustomButton({
isLoading,
children,
...props
}: CustomButtonProps) {
return (
<Button disabled={isLoading} {...props}>
{isLoading ? 'Loading...' : children}
</Button>
)
}
🔧 常见模式
表单处理:
- 使用 Server Actions 进行表单提交
- 使用
react-hook-form与zod进行验证(Client Components) - 使用 Shadcn/ui 表单组件
带 Server Action 的表单示例:
// app/actions/posts.ts
'use server'
import { z } from 'zod'
const createPostSchema = z.object({
title: z.string().min(1),
content: z.string().min(1),
})
export async function createPost(formData: FormData) {
const rawData = {
title: formData.get('title'),
content: formData.get('content'),
}
const validated = createPostSchema.parse(rawData)
// ... 创建 post 逻辑
redirect('/posts')
}
元数据:
import { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Posts',
description: 'List of all posts',
openGraph: {
title: 'Posts',
description: 'List of all posts',
},
}
核心原则
- Server Components 优先:默认使用 Server Components,仅在需要时使用 Client Components
- App Router 结构:使用
app/目录的基于文件的路由 - Shadcn/ui 组件:使用预置的可访问组件
- Tailwind CSS:实用优先的样式,搭配
cn()辅助函数 - TypeScript 严格:无
any,显式类型 - 性能:使用 Server Components,优化图片,需要时懒加载
- 文件组织:功能放在
app/features/,共享组件放在components/ - 导入别名:使用
@/前缀实现干净导入
快速参考:文件结构
app/
layout.tsx # 根布局
page.tsx # 首页
globals.css # 全局样式
(routes)/
posts/
page.tsx # 文章列表页
[id]/
page.tsx # 文章详情页
loading.tsx # 加载 UI
error.tsx # 错误 UI
features/
posts/
components/
PostList.tsx # 功能组件
actions/
posts.ts # Server Actions
components/
ui/ # Shadcn/ui 组件
button.tsx
card.tsx
lib/
utils.ts # 工具函数 (cn, 等)
hooks/
use-mobile.ts # 自定义 hooks
现代组件模板(快速复制)
Server Component:
// app/components/PostCard.tsx
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import type { Post } from '@/types/post'
interface PostCardProps {
post: Post
}
export function PostCard({ post }: PostCardProps) {
return (
<Card>
<CardHeader>
<CardTitle>{post.title}</CardTitle>
</CardHeader>
<CardContent>
<p>{post.content}</p>
</CardContent>
</Card>
)
}
Client Component:
// app/components/PostForm.tsx
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
export function PostForm() {
const [title, setTitle] = useState('')
const [content, setContent] = useState('')
return (
<form>
<Input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder='Title'
/>
<Input
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder='Content'
/>
<Button type='submit'>Submit</Button>
</form>
)
}