如何使用 css 定位 svelte 中的组件?

How to target a component in svelte with css?

我该怎么做:

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

<Nested />

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

我看了一下,没有发现任何相关内容(可能 here),所以这里有一个替代方法,即在您的自定义组件周围添加 <div>

<style>
.Nested {
    color: blue;
}
</style>
<div class="Nested">
   <Nested />
</div>

也许你会找到一些东西,但这个有效。

我能想到的唯一方法是添加一个额外的 div 元素。

App.svelte

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

<style>
    div :global(.style-in-parent) {
        color: green;
    }
</style>

<div>
    <Nested />  
</div>

Nested.svelte

<div class="style-in-parent">
    Colored based on parent style
</div>

多个嵌套元素

如果您使用多个 Nested 组件,您甚至可以允许 class 名称是动态的并允许使用不同的颜色。这是 link to a working example.

您需要使用 export let 将 props 传递给父组件,然后将这些 props 绑定到 class 或子组件中的样式。

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

<!-- 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 选择器,但只需将一个特定的 ref 添加到子元素中正在设置样式的元素,如下所示:

<!-- 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>

这确保全局仅影响其预期的子元素内的确切 ref 元素,而不影响任何其他 classes 或本机元素。你可以看到它的实际效果 at this REPL link

使用 :global(*) 是最简单的解决方案。

例如,如果您想为所有直接子级设置样式,则无需在子级中指定 class

在父组件中:

<style>
  div > :global(*) {
    color: blue;
  }
<style>

<div>
  <Nested />
<div>

嵌套为蓝色。

您可以使用内联样式和 $$props...

<!-- in parent component -->

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

<Nested style="background: green; color: white; padding: 10px; text-align: center; font-weight: bold" />
<!-- in Nested.svelte -->

<script>
    let stylish=$$props.style
</script>

<div style={stylish}>
    Hello World
</div>

REPL

我的做法是这样的:

<style lang="stylus">
  section
    // section styles

    :global(img)
    // image styles
</style>

这会生成 css 选择器,例如 section.svelte-15ht3eh img,它只影响 section 标签的子 img 标签。

没有类或其中涉及的技巧。