ข้ามไปยังเนื้อหา

Expressions

template expression ของ Astro หน้าตาแทบจะเหมือน JSX เลย คุณใช้ {expr} เพื่อฝัง JavaScript expression ใด ๆ ความแตกต่างที่สำคัญ: Astro ประเมิน expression นั้น ครั้งเดียว ตอน build/server time แล้วเขียนออกมาเป็น static HTML ไม่มี virtual DOM ไม่มีการ re-render ไม่มีการอัปเดตแบบ reactive

React
// Stats.jsx
export default function Stats({ count, label }) {
const doubled = count * 2;
return (
<div>
<span>{label}: {count}</span>
<span>Doubled: {doubled}</span>
</div>
);
}
Astro
---
// Stats.astro
const { count, label } = Astro.props;
const doubled = count * 2;
---
<div>
<span>{label}: {count}</span>
<span>Doubled: {doubled}</span>
</div>

JSX ใช้ {condition && <El />} และ ternary ส่วน Astro ก็ใช้ syntax เดียวกันเป๊ะ

React
// Alert.jsx
export default function Alert({ type, message }) {
return (
<div>
{type === "error" && (
<p className="error">{message}</p>
)}
{type !== "error" && (
<p className="info">{message}</p>
)}
</div>
);
}
Astro
---
// Alert.astro
const { type, message } = Astro.props;
---
<div>
{type === "error" && (
<p class="error">{message}</p>
)}
{type !== "error" && (
<p class="info">{message}</p>
)}
</div>

ternary ทำงานเหมือนกันทุกประการ: {isLoggedIn ? <Dashboard /> : <Login />}

React
// TagList.jsx
export default function TagList({ tags }) {
return (
<ul>
{tags.map((tag) => (
<li key={tag}>{tag}</li>
))}
</ul>
);
}
Astro
---
// TagList.astro
const { tags } = Astro.props;
---
<ul>
{tags.map((tag) => (
<li>{tag}</li>
))}
</ul>

Astro ไม่ ต้องการ prop key บน item ของ list เพราะไม่มีการ diff แบบ virtual DOM list จะถูก render ออกมาเป็น HTML ครั้งเดียวแล้วจบ

Astro
---
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>
คุณเขียน `{items.map((i) => <li>{i}</li>)}` ใน Astro template โค้ดนี้ทำงานเมื่อใด?
item ของ list ใน Astro ที่ render ด้วย `.map()` ต้องการ prop `key` หรือไม่?
expression ใด render paragraph เฉพาะเมื่อ `isAdmin` เป็น true ใน Astro template ได้อย่างถูกต้อง?