【问题标题】:CSS selectors not working as expected when using each and components in svelte在 svelte 中使用 each 和组件时,CSS 选择器无法按预期工作
【发布时间】:2021-10-29 09:44:17
【问题描述】:

当我的组件中可能有内部元素时,为什么 svelte 声明未使用的 CSS 选择器?

<div class="users">
    {#each [1,2,3,4,5] as id}
        <User name={id} />
    {/each}
</div>

<style>
    .users > * {
        margin-right: 5px;
    }
</style>

错误: Unused CSS selector ".users &gt; *" (12:4)

回复: https://svelte.dev/repl/6c8b4a6a808c4aee80e51af58b4fcda4?version=3.44.0

用户是一个普通的 div。不确定我是否应该使用其他模式来实现这一点。

【问题讨论】:

  • 认为你的“容器”类应该是“用户”?

标签: css css-selectors svelte


【解决方案1】:

多件事:

  • 我在你的代码中没有看到 users 类,div 有一个类 container,我猜你的意思是那个
  • Svelte 将所有样式限定为当前组件,这意味着子元素不是目标元素。在您的情况下,您希望定位 div 的任何直接子级,但元素位于 User 内,因此这不起作用

解决方案:使用:global 告诉 Svelte 不要将选择器范围限定为当前组件:

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

<div class="users">
    {#each [1,2,3,4,5] as id}
        <User name={id} />
    {/each}
</div>

<style>
    /* you could also write :global(.users > *) but that
       would also target any "users" class somewhere else */
    .users > :global(*) {
        border: 3px solid teal;
    }
</style>

【讨论】:

    【解决方案2】:

    在 Svelte 中,css 默认作用于组件,因此在组件内部定义的样式在其他任何地方都不起作用。 (组件内的样式元素会获得一个额外的类,例如 'svelte-1g7lik1')

    'users' div 是除 User 组件之外的 - 它不受样式影响 - 为空,因此声明对任何内容都没有影响,因此是多余的

    您可以通过将 css 语句包装在 :global() 中来解决问题

    看到这个REPL

    <script>
    import User from './User.svelte'
    </script>
    
    <div class="users">
        {#each [1,2,3,4,5] as id}
            <User name={id} />
        {/each}
    </div>
    
    <style>
        .users > :global(*){
          border: 3px solid teal;
        }
    
        /*>> .users.svelte-16kesww>* {...} in bundle.css  */
          >> affects 'childcomponent-children'
    
      
        :global(.users > *) {  
            box-shadow: 2px 3px 0 0 pink;
        }
    
        /*>> .users > * {...} in bundle.css
          >> affects globally all children of elements with class 'users' */
    </style>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2022-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多