Astro 组件 Props
Props
Props 是「父组件传给子组件的数据」,子组件通过 Astro.props 读取,从而渲染出不同内容,它是组件复用的基础。
读取基本 Props
---
// src/components/Greeting.astro
const { name } = Astro.props;
---
<p>你好,{name}</p>
在页面里传入:
---
import Greeting from '../components/Greeting.astro';
---
<Greeting name="小明" />
<Greeting name="小红" />
设置默认值
如果调用方没传某个属性,可以给它一个默认值。
---
const { name = '访客' } = Astro.props;
---
<p>你好,{name}</p>
不传 name 时会显示「你好,访客」。
接收多个 Props
---
const { title, href, external = false } = Astro.props;
---
<a href={href} target={external ? '_blank' : undefined}>{title}</a>
调用:
<MyLink title="Astro 官网" href="https://astro.build" external={true} />
用 TypeScript 定义类型
在脚本里给 Props 写接口,编辑器会提示你该传什么、传错会高亮。
---
interface Props {
title: string;
count?: number;
}
const { title, count = 0 } = Astro.props;
---
<h2>{title}</h2>
<p>数量:{count}</p>
? 表示可选属性,这种方式在大型项目里非常实用,能提前发现低级错误。
接收子元素(children)
除了显式属性,组件还能接收「标签之间的内容」,通过 Astro.props 的隐含 children,或用插槽语法 <slot />。
---
const { title } = Astro.props;
---
<section>
<h2>{title}</h2>
<slot />
</section>
调用:
<Card title="公告">
<p>这是卡片里的内容</p>
</Card>
这里 <p> 会渲染到 <slot /> 的位置,插槽我们会在后面章节(Astro 插槽 slot)单独讲。
传递整个对象
如果数据是一个对象,可以一次性展开传入。
---
const post = { title: '文章', href: '/a' }; // 用展开语法把整个对象作为 props 传给组件
---
<PostCard {...post} />
子组件里仍然用 Astro.props.title 读取。