如何使用 svelte 将其余道具传递给 HTML 元素?

How to pass the rest of the props to an HTML element using svelte?

我遇到了一个问题:

我有一个 svelte 组件,它与许多道具一起使用:

<script>
    export let foo;
    export let bar;

</script>

而且,我想直接将一些道具传递给我的 HTML 元素。 所以我的解决方案是:

<script>
    export let foo;
    export let bar;

    const {
        foo,
        bar,
        ...other
    } = $$props;
</script>

<button {...other}>
    Some action
</button>

这个问题很大: 当我改变一些像“class”这样的道具时,组件不会更新。

<MyComponent {foo} {bar} class={condition ? 'one' : 'two'} />

解决这个问题的更好方法是什么?我的意思是,我必须支持不同的道具,而不仅仅是“class”一个。 我如何将其余道具传递给 HTML-element

嗯...通过 class 这种方式对我有用。看到这个 REPL.

App.svelte

<script>
    import MyComponent from './MyComponent.svelte'
    
    let checked
</script>

<label>
  <input type=checkbox bind:checked />
    Blue?
</label>

<MyComponent class={checked ? 'blue' : 'red'} />

MyComponent.svelte

<script>
  export let foo
  export let bar
</script>

<pre>foo={foo} bar={bar}</pre>

<button {...$$restProps}>
  Some button
</button>

<style>
    :global(.red) {
        color: red;
    }
    :global(.blue) {
        color: blue;
    }
</style>

一些注意事项...

Svelte 最近推出了 $$restPropsdocs -- 本节结尾),这可能更适合手动过滤道具。

您示例中的这段代码 不是反应式的:

    const {
        foo,
        bar,
        ...other
    } = $$props;

只在创建组件时执行一次。当 props 更改时它不会更新,这可能解释了为什么您随后更改的 props (class={condition ? 'one' : 'two'}) 没有反映出来。

如果你需要做这样的事情(比如因为你需要比 $$restProps 提供的开箱即用更多的控制),你需要把它放在一个反应​​块中 ($:) .

例如:

$: ({ foo, bar, ...other } = $$props)

上面的JS语法等价于下面的,更冗长,替代:

let foo
let bar
$: {
  foo = $$props.foo
  bar = $$props.bar
}