css-如何在svelte中定位组件?

时间:2019-07-11 12:01:16

标签: javascript svelte svelte-component

我该怎么做?

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

<Nested />

即如何将样式应用于其父级的组件?

6 个答案:

答案 0 :(得分:8)

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

您可以在要动态设置样式的子元素上放置样式标签,并使用导出给父元素的变量直接确定样式的值,然后在标签上分配颜色,如下所示:< / p>

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

这可确保global仅影响其预期使用的子对象中的确切ref元素,而不影响其他任何类或本机元素。您可以在操作中at this REPL link

看到它

答案 1 :(得分:4)

您可以使用内联样式和$$ 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

答案 2 :(得分:3)

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

例如,如果要设置所有直接子级的样式,则无需在子级中指定类

在父组件中:

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

<div>
  <Nested />
<div>

嵌套将为蓝色。

答案 3 :(得分:1)

我的做法是这样的:

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

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

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

不涉及任何课程或技巧。

答案 4 :(得分:0)

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

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

也许您会发现一些东西,但这一项可行。

答案 5 :(得分:0)

我唯一想到的方法是添加一个额外的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组件,则甚至可以允许类名是动态的,并允许使用不同的颜色。这是rsyslog configuration