Props
ใน React props จะเข้ามาเป็น argument ตัวแรกของ component function แต่ใน Astro props จะเข้ามาผ่าน object ส่วนกลางชื่อ Astro.props ซึ่งคุณ destructure ออกมาใน frontmatter ด้วย syntax การ destructure แบบเดียวกับที่คุณรู้อยู่แล้ว
การรับ props
หัวข้อที่มีชื่อว่า “การรับ props”// Button.jsxexport default function Button({ label, variant = "primary" }) { return ( <button className={`btn btn--${variant}`}> {label} </button> );}
// Usage:// <Button label="Save" />// <Button label="Delete" variant="danger" />---// Button.astroconst { label, variant = "primary" } = Astro.props;---<button class={`btn btn--${variant}`}> {label}</button>
<!-- Usage:<Button label="Save" /><Button label="Delete" variant="danger" />-->สองสิ่งที่ควรสังเกต:
Astro.propsคือตัวเทียบเท่าของ props object ใน React ให้ destructure ออกมาแบบเดียวกับที่คุณทำกับ parameter ของฟังก์ชัน- ค่า default ทำงานด้วย default ของการ destructure ใน JavaScript มาตรฐาน (
= "primary")
TypeScript: interface Props
หัวข้อที่มีชื่อว่า “TypeScript: interface Props”Astro component รองรับ TypeScript ในตัวอยู่แล้ว ประกาศ interface Props (หรือ type Props) ใน frontmatter แล้ว compiler จะบังคับใช้ type นั้นตอน build time
// Card.tsxinterface Props { title: string; description?: string; href: string;}
export default function Card({ title, description = "", href }: Props) { return ( <a href={href} className="card"> <h2>{title}</h2> {description && <p>{description}</p>} </a> );}---// Card.astrointerface Props { title: string; description?: string; href: string;}
const { title, description = "", href } = Astro.props;---<a href={href} class="card"> <h2>{title}</h2> {description && <p>{description}</p>}</a>การประกาศ interface Props คือ pattern แบบ idiomatic ของ Astro language server ของ Astro จะอ่าน type นี้เพื่อช่วยให้ editor autocomplete ได้ตอนที่คุณนำ component ไปใช้
ตัวอย่างที่รันได้จริง
หัวข้อที่มีชื่อว่า “ตัวอย่างที่รันได้จริง”---
interface Props {
name: string;
role?: string;
color?: string;
}
const { name, role = "Developer", color = "#6366f1" } = Astro.props;
---
<html lang="en">
<head><meta charset="utf-8" /><title>Props demo</title></head>
<body style="font-family:sans-serif;padding:2rem">
<div style={`border-left:4px solid ${color};padding-left:1rem`}>
<h1>{name}</h1>
<p style="color:#888">{role}</p>
</div>
</body>
</html>