[英]How can I receive arbitrary props in a Svelte component and pass to a child component?
I want to receive arbitrary props from "above" and spread them onto an <input>
, as shown here where inputProps
would become an object containing any additional props set on this component (similar to python's **kwargs
, in case you're familiar):我想从“above”接收任意道具并将它们传播到
<input>
,如下所示,其中inputProps
将成为包含在此组件上设置的任何其他道具的对象(类似于 python 的**kwargs
,以防你熟悉):
<script>
export let id;
export ...inputProps;
</script>
<div>
id: {id}
<input {...inputProps} />
</div>
Can you point me toward the correct Svelte mechanism for accomplishing something like this?你能指出正确的 Svelte 机制来完成这样的事情吗? I have a feeling that I'm asking the wrong question, but I need a svelte developer to set me straight.
我有一种感觉,我问错了问题,但我需要一个苗条的开发人员来纠正我。 Should I use a slot instead?
我应该改用插槽吗? Or learn about actions / "the use directive"?
或者了解操作/“使用指令”?
You can use $$props
to access all the props given to a component.你可以使用
$$props
来访问所有赋予组件的 props。
$$props
references all props that are passed to a component – including ones that are not declared withexport
.$$props
引用所有传递给组件的 props——包括那些没有用export
声明的 props。 It is useful in rare cases, but not generally recommended, as it is difficult for Svelte to optimise.它在极少数情况下很有用,但通常不推荐使用,因为 Svelte 很难优化。
<!-- 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 now also offers $$restProps
. Svelte 现在还提供
$$restProps
。 See the Svelte API Docs - Attributes and props .请参阅Svelte API 文档 - 属性和道具。
$$props
references all props that are passed to a component – including ones that are not declared with export. $$props
引用所有传递给组件的 props——包括那些没有用 export 声明的 props。 It is useful in rare cases, but not generally recommended, as it is difficult for Svelte to optimise.它在极少数情况下很有用,但通常不推荐使用,因为 Svelte 很难优化。
<Widget {...$$props}/>
$$restProps
contains only the props which are not declared with export. $$restProps
仅包含未通过导出声明的道具。 It can be used to pass down other unknown attributes to an element in a component.它可用于将其他未知属性传递给组件中的元素。
<input {...$$restProps}>
While exporting you don't need to use the spread operator导出时您不需要使用扩展运算符
<script>
export let id;
export inputProps;
</script>
<div>
id: {id}
<input {...inputProps} />
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.