首页 > 解决方案 > 动态 html 元素作为组件

问题描述

我想在 svelte 中创建一个 header 组件,我可以在其中指定我想要的 h1 到 h6 中的哪个作为组件。那是

<HeaderComponent component={h2} />
// or
<HeaderComponent kind="4" /> // for h4

但是,第一个不知道h2是什么,而第二个似乎只是归结为一个我不喜欢的长 if-else 语句。有没有一些简单的方法来实现这种事情?

实际的组件比 h1-h6 的简单包装器更复杂,所以我不能只使用 h1-h6 或使用插槽,因为我想像 id 一样向 h1-h6 组件添加属性。我尝试使用 svelte:component,但同样,svelte 不能仅识别 h1。

这个问题有一个简单的解决方案,还是我只是做一个长的 if-else 块?

标签: svelte

解决方案


尽管在 Svelte 中实际上还不可能(请参阅https://github.com/sveltejs/svelte/issues/2324),但有一个使用内置{@html}函数的简单解决方法。

App.svelte

<script>
    import Header from "./Header.svelte";
</script>

<main>
      <Header headerType="h1" />
</main>

页眉.svelte

<script>
    export let headerType;
</script>

{@html `<${headerType}>Hello, World!</${headerType}>`}

如果不使用 if 语句字符串,这似乎是可以正确实现的唯一方法。

在此处查看 Svelte REPL 。


推荐阅读