[英]How can I switch the underlying markup of a Svelte component without an "if"?
谁能建议一种更好的方法来实现可以是a
或button
的组件? 我同意这种方法,但除了a
上的href
和button
上的on:click
之外,它们之间的所有内容都是重复的:
{#if url}
<a class="button {classes}"
class:button--solid={!outlined}
class:button--outlined={outlined}
{disabled}
bind:this={element}
href={url}
>
<span class="label"><slot /></span>
</a>
{:else}
<button class="button {classes}"
class:button--solid={!outlined}
class:button--outlined={outlined}
{disabled}
bind:this={element}
on:click
>
<span class="label"><slot /></span>
</button>
{/if}
谢谢!
你可以使用 <svelte:component this={selected.component}/>
如前所述,您可以使用<svelte:component>
但我认为这对于您的用例来说太过分了(您需要为 vanilla button
和a
创建 2 个单独的组件)。 看起来你只需要更好的可读性。 获得更多 DRY 的解决方法是使用spread props 。
<script>
export let url;
const classes = 'class-1 class-2';
const outlined = true;
const disabled = true;
$: props = {
class: `button ${classes} ${outlined ? 'button--outlined' : 'button--solid'}`,
disabled
}
</script>
{#if url}
<a {...props} href={url}><slot/></a>
{:else}
<button {...props} on:click><slot/></button>
{/if}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.