Expressions
template expression ของ Astro หน้าตาแทบจะเหมือน JSX เลย คุณใช้ {expr} เพื่อฝัง JavaScript expression ใด ๆ ความแตกต่างที่สำคัญ: Astro ประเมิน expression นั้น ครั้งเดียว ตอน build/server time แล้วเขียนออกมาเป็น static HTML ไม่มี virtual DOM ไม่มีการ re-render ไม่มีการอัปเดตแบบ reactive
การฝังค่า
หัวข้อที่มีชื่อว่า “การฝังค่า”// Stats.jsxexport default function Stats({ count, label }) { const doubled = count * 2; return ( <div> <span>{label}: {count}</span> <span>Doubled: {doubled}</span> </div> );}---// Stats.astroconst { count, label } = Astro.props;const doubled = count * 2;---<div> <span>{label}: {count}</span> <span>Doubled: {doubled}</span></div>เงื่อนไข (Conditionals)
หัวข้อที่มีชื่อว่า “เงื่อนไข (Conditionals)”JSX ใช้ {condition && <El />} และ ternary ส่วน Astro ก็ใช้ syntax เดียวกันเป๊ะ
// Alert.jsxexport default function Alert({ type, message }) { return ( <div> {type === "error" && ( <p className="error">{message}</p> )} {type !== "error" && ( <p className="info">{message}</p> )} </div> );}---// Alert.astroconst { type, message } = Astro.props;---<div> {type === "error" && ( <p class="error">{message}</p> )} {type !== "error" && ( <p class="info">{message}</p> )}</div>ternary ทำงานเหมือนกันทุกประการ: {isLoggedIn ? <Dashboard /> : <Login />}
การ render list
หัวข้อที่มีชื่อว่า “การ render list”// TagList.jsxexport default function TagList({ tags }) { return ( <ul> {tags.map((tag) => ( <li key={tag}>{tag}</li> ))} </ul> );}---// TagList.astroconst { tags } = Astro.props;---<ul> {tags.map((tag) => ( <li>{tag}</li> ))}</ul>Astro ไม่ ต้องการ prop key บน item ของ list เพราะไม่มีการ diff แบบ virtual DOM list จะถูก render ออกมาเป็น HTML ครั้งเดียวแล้วจบ
ตัวอย่างที่รันได้จริง
หัวข้อที่มีชื่อว่า “ตัวอย่างที่รันได้จริง”---
const fruits = ["Apple", "Banana", "Cherry", "Date"];
const today = new Date().toLocaleDateString("en-US", { weekday: "long" });
const isWeekend = [0, 6].includes(new Date().getDay());
---
<html lang="en">
<head><meta charset="utf-8" /><title>Expressions demo</title></head>
<body style="font-family:sans-serif;padding:2rem">
<h1>Today is {today}</h1>
{isWeekend && <p style="color:green">It is the weekend!</p>}
{!isWeekend && <p style="color:#555">It is a weekday.</p>}
<h2>Fruits ({fruits.length})</h2>
<ul>
{fruits.map((fruit) => <li>{fruit}</li>)}
</ul>
</body>
</html>