Iva*_*S95 4 html css tailwind-css astro
我有一个现有的 Astro 组件,它的模板中已经包含了一些类;但是我试图在不同的视图上重用此组件,并仅在该视图上更改其标题的颜色。
所以我读到文档说我可以传递一个class
prop 将类从父级添加到子级;但是,我不明白如何保留组件中的现有类并覆盖某些内容或将另一个类添加到已有的类中。
<ExpansionQuestion question={question.question}>
<Fragment slot="body" set:html={question.answer} />
</ExpansionQuestion>
Run Code Online (Sandbox Code Playgroud)
ExpansionQuestion
根元素:
<details
class="group bg-blue-gray duration-300 rounded-lg p-4 w-full shadow-md focus:outline-none focus:ring-0"
>
Run Code Online (Sandbox Code Playgroud)
我只想在一个特定视图上bg-secondary
向元素添加一个不同的类details
,其余类应该在各处保持相同。
是否有可能做到这一点?
这里的一种好方法是使用Astro\xe2\x80\x99sclass:list
指令。这让您可以更轻松地组合各种类。
在您的示例中,您可能会执行以下操作:
\n将附加类传递给您使用它的组件(这里使用 prop bg
,但您可以根据任何情况调整它):
<ExpansionQuestion question={question.question} bg="bg-secondary">\n <Fragment slot="body" set:html={question.answer} />\n</ExpansionQuestion>\n
Run Code Online (Sandbox Code Playgroud)\n使用 prop 来控制组件中的背景ExpansionQuestion.astro
:
---\nconst { bg } = Astro.props;\n---\n<details\n class:list={[\n "group duration-300 rounded-lg p-4 w-full",\n "shadow-md focus:outline-none focus:ring-0",\n bg || "bg-blue-gray"\n ]}\n>\n
Run Code Online (Sandbox Code Playgroud)\nAstro 会自动组合数组中的项目class:list
,在这种情况下,bg
如果传递了 prop,将使用该 prop,但如果没有传递 prop,则默认为蓝灰色。
接受class
子组件中的 prop 并将其应用到根元素。解构时,必须重命名,因为class
是JavaScript 中的保留字。此外, 2023 年 10 月 13 日发布的文档补丁强调,您还应该使用其余参数,以便作用域样式起作用。
子组件:
---
const { class: className, ...rest } = Astro.props
---
<div class:list={['child-component', className]} {...rest}>
Child component
</div>
<style>
.child-component {
border: 2px solid blue;
}
</style>
Run Code Online (Sandbox Code Playgroud)
从父级使用它:
---
import ChildComponent from '...'
---
<div class="parent">
<ChildComponent class="my-child-component"/>
</div>
<style>
.my-child-component {
background: red;
}
</style>
Run Code Online (Sandbox Code Playgroud)
文档中有更多相关内容