Astro - 基礎入門3.第三課練習題實作

更新 發佈閱讀 5 分鐘

題目

任務目標: 建立一個動態的「顯示/隱藏」詳細資訊組件。

  1. 使用你熟悉的框架(React, Vue 或純 JS 的 <script> 標籤,建議練習 React)。
  2. 建立一個 DescriptionControl.jsx 組件。
  3. 該組件預設只顯示一段文字的前 20 個字,點擊「閱讀更多」按鈕後才顯示完整內容。
  4. 將這個組件放在你的 about.astro 頁面中。
  5. 實驗題: 試著在瀏覽器開發者工具 (F12) 的 Network 分頁觀察。當你使用 client:visible 時,重新整理頁面,JS 檔案是否是在你「捲動到組件位置」時才出現?

目前專案結構

📁 .astro/
📁 .vscode/
📁 node_modules/
📁 public/
└─ favicon.svg
📁 src/
├─ 📁 components/
│ └─ LikeButton.jsx
├─ 📁 content/
│ ├─ 📁 blog/
│ │ └─ post-1.md
│ └─ config.ts
├─ 📁 layouts/
│ └─ BaseLayout.astro
└─ 📁 pages/
├─ 📁 posts/
│ └─ [id].astro
├─ blog.astro
└─ index.astro
.gitignore
astro.config.mjs
package-lock.json
package.json
README.md
tsconfig.json

1_新增 src/components/DescriptionControl.jsx

import { useState } from "react";

export default function DescriptionControl({ description }) {
  const [more, setMore] = useState(false);
  const _click = () => setMore(prev => !prev);
  return (
    <div>
      <p>
        {more ? description : description.substring(0, 20) + "..."}
      </p>
      <button onClick={_click}>
        {more ? "收起" : "閱讀更多"}
      </button>
    </div>
  )
}

2_修改 src/pages/about.astro

  1. 新增參數 description ,隨便找超過20個字的句子當作參數值
  2. html 區塊找一個地方放 DescriptionControl,設定 description 參數
  3. DescriptionControl 要記得設定 client:visible
    不然就會跟我一樣 : 怎麼按鈕沒反應 ?
---

import BaseLayout from '../layouts/BaseLayout.astro'
import DescriptionControl from '../components/DescriptionControl'
const pageTitle = '關於我'

const identity = {
  firstName: '小明',
  hobbies: ['reading', 'gaming', 'coding'],
}
const description =
  '這段文字旨在模擬實際使用中的描述欄位,長度超過二十個字以符合需求。'
---

<BaseLayout pageTitle={pageTitle} pageName="about">

  <h2>{identity.firstName}</h2>
  <h3>我的愛好</h3>

  <ul>
    {identity.hobbies.map((x) => <li>{x}</li>)}
  </ul>

  <h3>描述</h3>
  <DescriptionControl description={description} client:visible />
</BaseLayout>
留言
avatar-img
李昀瑾的沙龍
0會員
25內容數
李昀瑾的沙龍的其他內容
2026/01/09
題目 任務目標: 實作「動態路由」,讓點擊列表後能看到文章內容。 這在 Astro 中是非常經典的步驟,請嘗試完成以下開發:
2026/01/09
題目 任務目標: 實作「動態路由」,讓點擊列表後能看到文章內容。 這在 Astro 中是非常經典的步驟,請嘗試完成以下開發:
2026/01/09
Astro 5.1.x 的重點在於如何管理內容 以前我們可能要手動 fs.readFileSync,現在我們用 Content Layer API,它能讓你的 Markdown 檔案擁有強大的型別檢查 (Type Safety)。 第二課:Content Collections (內容集) ——
Thumbnail
2026/01/09
Astro 5.1.x 的重點在於如何管理內容 以前我們可能要手動 fs.readFileSync,現在我們用 Content Layer API,它能讓你的 Markdown 檔案擁有強大的型別檢查 (Type Safety)。 第二課:Content Collections (內容集) ——
Thumbnail
2026/01/08
Astro - 基礎入門1.第一課練習題實作
2026/01/08
Astro - 基礎入門1.第一課練習題實作
看更多