如何解决如何创建使用嵌套组件属性的 Svelte 组件?
我正在尝试创建一个使用嵌套 Icon 组件的 IconButton 组件。我不知道如何使用 IconButton 中 Icon 的 title
属性。最终我想做一些类似 <IconButton title="design" />
的事情,它会从那个标题道具中呈现正确的图标。
我的 Icon.svelte 组件:
<script>
export let title = "default";
export let width = "24px";
export let height = "24px";
export let focusable = false;
let icons = [
{
box: 24,title: "design",svg: `<path d="M5 8V20H9V8H5ZM3 7L7 2L11 7V22H3V7ZM19 16V14H16V12H19V10H17V8H19V6H15V20H19V18H17V16H19ZM14 4H20C20.2652 4 20.5196 4.10536 20.7071 4.29289C20.8946 4.48043 21 4.73478 21 5V21C21 21.2652 20.8946 21.5196 20.7071 21.7071C20.5196 21.8946 20.2652 22 20 22H14C13.7348 22 13.4804 21.8946 13.2929 21.7071C13.1054 21.5196 13 21.2652 13 21V5C13 4.73478 13.1054 4.48043 13.2929 4.29289C13.4804 4.10536 13.7348 4 14 4V4Z" fill="white"/>`,},{
box: 24,title: "user",svg: `<path d="M12 14C14.2091 14 16 12.2091 16 10C16 7.79086 14.2091 6 12 6C9.79086 6 8 7.79086 8 10C8 12.2091 9.79086 14 12 14ZM12 8C13.1046 8 14 8.89543 14 10C14 11.1046 13.1046 12 12 12C10.8954 12 10 11.1046 10 10C10 8.89543 10.8954 8 12 8Z" /><path d="M4 22C2.89543 22 2 21.1046 2 20V4C2 2.89543 2.89543 2 4 2H20C21.1046 2 22 2.89543 22 4V20C22 21.1046 21.1046 22 20 22H4ZM4 4V20H7C7 17.2386 9.23858 15 12 15C14.7614 15 17 17.2386 17 20H20V4H4ZM15 20C15 18.3431 13.6569 17 12 17C10.3431 17 9 18.3431 9 20H15Z" />`,];
let displayIcon = icons.find((e) => e.title === title);
</script>
<svg
class={$$props.class}
{focusable}
{width}
{height}
viewBox="0 0 {displayIcon.box} {displayIcon.box}"
>
{@html displayIcon.svg}
</svg>
这个组件很好用,我可以毫无问题地使用图标 <Icon title="design" />
,而且它显然导出了一个 title
道具。我如何制作它以便我可以在父组件中使用该道具?
IconButton.svelte:
<script>
import Icon from './Icon.svelte'
</script>
<button title={title}>
<Icon />
</button>
我正在尝试在另一个组件中使用 IconButton 组件,如下所示:
<IconButton title="design" />
我得到的错误是 Cannot read property 'svg' of undefined
... 有什么想法吗?
我也试过:
<button title={Icon.title}>
<Icon />
</button>
------------
<button bind:title={title}>
<Icon {title} />
</button>
解决方法
您的 Icon
组件不是导出标题道具,而是导出对标题道具的控制。因此,在您的父组件 IconButton
中,您还应该使用 export let title
,然后将其传递给 Icon
组件。
IconButton.svelte
<script>
import Icon from './Icon.svelte'
export let title
</script>
<button {title}>
<Icon {title}/>
</button>
然后在您展示的任何其他文件中使用它<IconButton title="design" />
这是一个 REPL,这是关于 Exporting props 的 Svelte 教程。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。