如何在Svelte中使用css来定位组件?

2022-08-17 00:00:00 javascript svelte svelte-component

我该如何做这样的事情:

<style>
Nested {
    color: blue;
}
</style>

<Nested />

即如何将样式从其父组件应用到组件?


解决方案

您需要使用导出LET将道具传递给父组件,然后将这些道具绑定到子组件中的类或样式。

您可以在要动态设置样式的子项中的元素上放置一个样式标记,并使用为父项导出的变量直接确定样式值,然后在标记上分配颜色,如下所示:

<!-- in parent component -->

<script>
import Nested from './Nested.svelte';
</script>

<Nested color="green"/>
<!-- in Nested.svelte -->

<script>
export let color;
</script>

<p style="color: {color}">
    Yes this will work
</p>

优点是灵活性如果您只有一到两个要调整的样式,缺点是您不能从一个道具调整多个CSS属性。

您仍然可以使用:global选择器,但只需将特定引用添加到子级中正在设置样式的元素,如下所示:

<!-- in parent component -->

<script>
import Nested from './Nested.svelte';
</script>

<Nested ref="green"/>

<style>
:global([ref=green]) {
    background: green;
    color: white;
    padding: 5px;
    border-radius: .5rem;
}
</style>
<!-- in Nested.svelte -->

<script>
export let ref;
</script>

<p {ref}>
    Yes this will work also
</p>

这确保了GLOBAL只影响它打算用于的子级中的ref元素,而不影响任何其他类或本机元素。您可以在操作中看到它at this REPL link

相关文章