.astro Components
ใน React คุณเขียน component เป็นฟังก์ชัน JavaScript ที่ return JSX ออกมา ส่วนใน Astro คุณเขียน component เป็นไฟล์ .astro ที่เป็น superset ของ HTML ที่มีบล็อก JavaScript/TypeScript แบบ optional อยู่ด้านบนสุด เรียกว่า frontmatter
การปรับ mental model ที่สำคัญ: React function component ทำงานใน browser ทุกครั้งที่ re-render แต่ Astro component ทำงาน ครั้งเดียวตอน build time (หรือบนเซิร์ฟเวอร์) แล้วส่งออกมาเป็น HTML ล้วน ๆ โดย default จะมี JavaScript เป็นศูนย์ ไม่มี virtual DOM ไม่มีการ re-render ไม่มีต้นทุนของ hydration
โมดูลนี้จะพาคุณไล่ดูทุกองค์ประกอบของ .astro component โดยยึดโยงกับสิ่งที่คุณรู้อยู่แล้วจาก React
บทเรียนในโมดูลนี้
หัวข้อที่มีชื่อว่า “บทเรียนในโมดูลนี้”| บทเรียน | สิ่งที่คุณจะได้เรียนรู้ |
|---|---|
| Frontmatter & Template | บล็อก --- เทียบกับ function body ของ React |
| Props | Astro.props เทียบกับ props ของ React |
| Slots | <slot /> เทียบกับ children |
| Expressions | template expression เทียบกับ JSX |
| Importing Components | การประกอบ component ใน .astro |
| Server-Only & Scripts | JS เป็นศูนย์โดย default และวิธีเพิ่ม JS ฝั่ง browser |
.astro component ตัวแรกของคุณ
หัวข้อที่มีชื่อว่า “.astro component ตัวแรกของคุณ”React component และตัวเทียบเท่าในรูปแบบ .astro วางเทียบกัน:
// Greeting.jsxexport default function Greeting({ name }) { return <h1>Hello, {name}!</h1>;}---// Greeting.astroconst { name } = Astro.props;---<h1>Hello, {name}!</h1>และนี่คือแนวคิดเดียวกันในรูปแบบหน้าเว็บที่รันได้จริง:
---
const name = "React developer";
const year = new Date().getFullYear();
---
<html lang="en">
<head><meta charset="utf-8" /><title>Hello</title></head>
<body>
<h1>Hello, {name}!</h1>
<p>Built in {year}. No JavaScript shipped to the browser.</p>
</body>
</html>