简体   繁体   中英

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):

<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? 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 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.

Example ( 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 now also offers $$restProps . See the Svelte API Docs - Attributes and 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.

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

$$restProps contains only the props which are not declared with export. 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>

Working example with some sample code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM