題目
任務目標: 建立一個動態的「顯示/隱藏」詳細資訊組件。
- 使用你熟悉的框架(React, Vue 或純 JS 的
<script>標籤,建議練習 React)。 - 建立一個
DescriptionControl.jsx組件。 - 該組件預設只顯示一段文字的前 20 個字,點擊「閱讀更多」按鈕後才顯示完整內容。
- 將這個組件放在你的
about.astro頁面中。 - 實驗題: 試著在瀏覽器開發者工具 (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
- 新增參數
description,隨便找超過20個字的句子當作參數值 - html 區塊找一個地方放
DescriptionControl,設定description參數 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>
