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

Can I set svelte style css attribute values using variables passed in to a component

我想创建一个接收图像名称和路径的 svelte 组件。我想让组件使用 CSS.

将图像设置为 "background-image"

我已经尝试了以下似乎不起作用...

App.svelte:

中调用的组件
<Image image_url='./images/image1.jpg' />

Image.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>

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

background-image: url({image_url});

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

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

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

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

第二种,特别是如果您需要在多个地方使用值,是使用 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>

将 Svelte 块视为 CSS 黑盒。您不能像在浏览器中的 css 文件中一样使用 javascript 变量。

但是...由于它是一个 CSS 框,您始终可以使用 scss 并使用像 this one 这样的精巧预处理器编译您的块。那你就可以做

<script>
export let image_url;
</script>

<style lang="scss">
@import "my/path/to/variables";

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

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

<Image --background-image='url(./images/image1.jpg)' />

Image.svelte

    background-image: var(--background-image, url(./images/default.jpg));