我如何在 Svelte 组件中接收任意道具并传递给子组件?

How can I receive arbitrary props in a Svelte component and pass to a child component?

我想从 "above" 接收任意道具并将它们传播到 <input>,如此处所示,其中 inputProps 将成为一个对象,其中包含在此组件上设置的任何其他道具(类似于 python 的 **kwargs,以防您熟悉):

<script>
export let id;
export ...inputProps;
</script>

<div>
    id: {id}
    <input {...inputProps} />
</div>

你能指出正确的 Svelte 机制来完成这样的事情吗?我觉得我问错了问题,但我需要一个精明的开发人员来让我直截了当。我应该改用插槽吗?或了解操作 / "the use directive"?

导出时不需要使用展开运算符

<script>
 export let id;
 export inputProps;
</script>

<div>
 id: {id}
 <input {...inputProps} />
</div>

您可以使用 $$props 访问给定组件的所有属性。

$$props references all props that are passed to a component – including ones that are not declared with export. It is useful in rare cases, but not generally recommended, as it is difficult for Svelte to optimise.

示例 (REPL)

<!-- App.svelte -->
<script>
  import Child from './Child.svelte';
</script>

<Child id="foo" placeholder="bar" />

<!-- Child.svelte -->
<script>
  let id, inputProps;
  $: ({ id, ...inputProps } = $$props);
</script>

<div>
  id: {id}
  <input {...inputProps} />
</div>

Svelte 现在还提供 $$restProps。见 Svelte API Docs - Attributes and props.

$$props 引用传递给组件的所有 props – 包括未通过 export 声明的 props。它在极少数情况下很有用,但通常不推荐,因为 Svelte 很难优化。

<Widget {...$$props}/>

$$restProps 仅包含未通过导出声明的道具。它可用于将其他未知属性传递给组件中的元素。

<input {...$$restProps}>