我可以使用传递给组件的变量设置 svelte 样式的 css 属性值吗

bej*_*mes 10 syntax svelte

我想创建一个接收图像名称和路径的 svelte 组件。我想让组件使用 CSS 将图像设置为“背景图像”。

我尝试了以下似乎不起作用的方法...

App.svelte 中调用的组件

<Image image_url='./images/image1.jpg' />
Run Code Online (Sandbox Code Playgroud)

图像.Svelte

<script>
export let image_url;
</script>

<style>
.image{
    position:relative;
    opacity: 0.70;
    background-position:bottom;
    background-size: cover;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-image: url({image_url});
    min-height: 100%;
}
</style>

<div class="image">
  <p>some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)

当我检查组件时,background_image 的 css 是:

background-image: url({image_url});
Run Code Online (Sandbox Code Playgroud)

是否可以在 CSS 中转换变量?

Ric*_*ris 28

不会。组件样式在组件的所有实例之间共享,因为它们被静态提取到 .css 文件中,或者因为它们被注入到<style>所有组件引用的单个元素中。如果可以将变量直接放入组件的 中<style>,则意味着 Svelte 需要为每个实例创建封装样式,这将不利于性能并且会消耗更多内存。

有两种方法可以解决这个问题。第一种是对可以更改每个实例的任何内容使用内联样式:

<script>
export let image_url;
</script>

<style>
.image{
    position:relative;
    opacity: 0.70;
    background-position:bottom;
    background-size: cover;
    background-repeat: no-repeat;
    background-attachment: fixed;
    /* background-image: url({image_url}); */
    min-height: 100%;
}
</style>

<!-- <div class="image"> -->
<div class="image" style="background-image: url({image_url});">
  <p>some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)

第二种,特别是当你需要在多个地方使用值时,是使用 CSS 变量:

<script>
export let image_url;
</script>

<style>
.image{
    position:relative;
    opacity: 0.70;
    background-position:bottom;
    background-size: cover;
    background-repeat: no-repeat;
    background-attachment: fixed;
    /* background-image: url({image_url}); */
    background-image: var(--image);
    min-height: 100%;
}
</style>

<!-- <div class="image"> -->
<div class="image" style="--image: url({image_url});">
  <p>some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,我是 Svelte 的创建者,我写了那篇文章;)CSS-in-JS 有它的用途,但我通常不建议使用它来解决这个特定问题,这可能有点过头了 (8认同)
  • @RichHarris,如果这是*过度杀伤*,那么还有什么选择呢?我想将这些更改委托给组件,其中父组件可以提供“上下文”以在子组件的 css 样式中进行自定义,替代方案会破坏干净的分隔 (2认同)

coy*_*508 17

您现在可以直接将 css 变量作为 props 传递:https://svelte.dev/docs#template-syntax-component-directives---style-props

<Image --background-image='url(./images/image1.jpg)' />
Run Code Online (Sandbox Code Playgroud)

Image.svelte

background-image: var(--background-image, url(./images/default.jpg));
Run Code Online (Sandbox Code Playgroud)