<svelte:element>
<svelte:element this={expression} />
<svelte:element>
元素允许你渲染创作时未知的元素,例如因为它来自 CMS。存在的任何属性和事件监听器都将应用于该元素。
¥The <svelte:element>
element lets you render an element that is unknown at author time, for example because it comes from a CMS. Any properties and event listeners present will be applied to the element.
唯一支持的绑定是 bind:this
,因为 Svelte 的内置绑定不适用于通用元素。
¥The only supported binding is bind:this
, since Svelte’s built-in bindings do not work with generic elements.
如果 this
具有空值,则不会渲染元素及其子元素。
¥If this
has a nullish value, the element and its children will not be rendered.
如果 this
是 空元素 的名称(例如 br
)并且 <svelte:element>
具有子元素,则在开发模式下将抛出运行时错误:
¥If this
is the name of a void element (e.g., br
) and <svelte:element>
has child elements, a runtime error will be thrown in development mode:
<script>
let tag = $state('hr');
</script>
<svelte:element this={tag}>
This text cannot appear inside an hr element
</svelte:element>
Svelte 会尽力从元素的周围环境中推断出正确的命名空间,但这并不总是可行的。你可以使用 xmlns
属性将其显式化:
¥Svelte tries its best to infer the correct namespace from the element’s surroundings, but it’s not always possible. You can make it explicit with an xmlns
attribute:
<svelte:element this={tag} xmlns="http://www.w3.org/2000/svg" />
this
需要是有效的 DOM 元素标记,#text
或 svelte:head
之类的标记将不起作用。
¥this
needs to be a valid DOM element tag, things like #text
or svelte:head
will not work.