svelte - 动态 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 中实际上还不可能(请参阅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 。
推荐阅读
- javascript - 如何使用 Eclipse Paho JavaScript 客户端连接到 test.mosquitto.org?
- database - 如何修复查询结果末尾附加的空行
- typescript - IDE 承认变量存在,但 Typescript 给出编译器错误
- javascript - 如何向访问者不可见的刮板提供文本字符串
- python - 单击提交按钮后使用 Python 获取新 URL
- java - 如何从网页上的 json 数据创建对象?
- google-apps-script - onSubmit 触发器:表单的 GetEditResponseUrl 有时执行失败
- salesforce - Salesforce 中的记录类型是什么?您将在哪些用例中使用它们?
- python - 使用 DataFrame 和 pct_change() 计算年利率
- asp.net-core-mvc - 天蓝色 Web 应用计划中的 Azure AD B2C 返回 url