svelte - 如何在 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>
:
该
<svelte:component>
元素使用指定为 this 属性的组件构造函数动态呈现组件。当属性改变时,组件被销毁并重新创建。
例如:
<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
推荐阅读
- stm32 - STM32:通过DMA直接连接外设I2C和UART
- javascript - 类型参数不能分配给类型参数(它们是同一件事)
- android - 是否可以将两个布尔值与 && 进行比较?
- ios - 当用户在 iOS 订阅中输入计费重试时应该采取什么操作?
- mysql - 如何从 MySQL 中的表达式或字符串将位插入 BIT 字段?
- swift - MKMapView 边界
- python - 使用可选子字符串拆分字符串
- python - 如何在 ipython 中修复“DistributionNotFound:'jsonschema' 分布 ...”
- rust - 如何从 Rust 生成完全链接的可执行 LLVM 位码文件?
- ruby-on-rails - 组合两个选择语句的结果而不返回数组的最佳方法?