如何在 Svelte 中动态渲染组件?

How to dynamically render components in Svelte?

我正在尝试遍历数组以呈现值为 type 的组件。

<script>

import One from './One.svelte';    
import Two from './Two.svelte';
import Three from './Three.svelte';

const contents = [
 {type: 'One'},
 {type: 'Two'},
 {type: 'Three'},
 {type: 'One'}
]

</script>

{#each contents as content}
    <{content.type} />
{/each}

期望的输出:

<One />
<Two />
<Three />
<One />

最好的方法是什么?

使用<svelte:component>:

The <svelte:component> element renders a component dynamically, using the component constructor specified as the this property. When the property changes, the component is destroyed and recreated.

例如:

<script>
    import One from './One.svelte';    
    import Two from './Two.svelte';

const contents = [
 One,
 Two
]
</script>

{#each contents as content}
    <svelte:component this={content}/>
{/each}

https://svelte.dev/repl/e56e75ad9b584c44930fe96489a36e14?version=3.31.2