简单 Blog 使用 Routing
你将构建什么
blog 使用 home page listing 所有 posts, and post detail page for 每个 post. Uses React Router for 导航之间列表 and detail views 使用动态 URL params.
学习目标
- 设置 React Router 使用 routes
- 导航之间 pages 使用链接
- Use 动态 route params (useParams)
- 渲染不同 pages conditionally
前置要求
- React Router 基础
- 组件 and Props
- 列表渲染
步骤
- 1
定义 blog post 数据
创建数组的 blog post 对象使用 id, title, and 内容.
代码const posts = [ { id: 1, title: "Getting Started with React", content: "React is..." }, { id: 2, title: "Understanding Hooks", content: "Hooks let you..." }, { id: 3, title: "State Management", content: "There are many ways..." }, ];预期结果
Blog 数据是 ready.
- 2
创建 Home and PostDetail 组件
Home 列表所有 posts as 链接. PostDetail 读取 :id param 使用 useParams and shows matching post.
代码function Home() { return ( <div> <h1>Blog</h1> {posts.map(p => ( <div key={p.id}> <Link to={`/post/${p.id}`}>{p.title}</Link> </div> ))} </div> ); } function PostDetail() { const { id } = useParams(); const post = posts.find(p => p.id === parseInt(id)); return ( <div> <Link to="/">Back</Link> <h1>{post.title}</h1> <p>{post.content}</p> </div> ); }预期结果
Home shows post 链接. PostDetail shows 单个 post.
- 3
设置 router
Wrap app in BrowserRouter and 定义 routes for Home and PostDetail.
代码<BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/post/:id" element={<PostDetail />} /> </Routes> </BrowserRouter>预期结果
点击 post 链接导航到 它的 detail page. 后面返回到 列表.
- 4
添加状态管理与事件处理
使用 useState 管理组件状态,为交互元素添加 onClick/onChange 事件处理。状态是 React 组件的核心,事件处理让组件响应用户操作。
代码import { useState } from "react"; export function MyComponent() { const [count, setCount] = useState(0); const [text, setText] = useState(""); return ( <div> <button onClick={() => setCount(c => c + 1)}> Count: {count} </button> <input value={text} onChange={(e) => setText(e.target.value)} /> </div> ); }预期结果
点击按钮计数递增;输入框内容随键入实时更新。
- 5
添加 Props 验证与组件拆分
为组件定义 Props 接口(TypeScript)或 propTypes,将大组件拆分为更小的子组件。类型安全的 Props 让组件接口清晰、可复用。
代码interface ChildProps { label: string; value: number; onChange: (v: number) => void; } function Child({ label, value, onChange }: ChildProps) { return ( <label> {label} <input type="number" value={value} onChange={(e) => onChange(Number(e.target.value))} /> </label> ); }预期结果
子组件接收类型安全的 Props;父组件可复用子组件渲染多个字段。
自己动手试试
你学到了什么
你学习到 构建 multi-page app 使用 React Router: 定义 routes, 导航使用链接, 读取动态 URL params 使用 useParams, and structuring app 使用多个 views. 这个是 基础的 任何 React SPA 使用导航.
相关资源
相关课程
- React Router
Routing and 导航.
- 组件
Page 组件.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。