如何创建一个使用嵌套组件属性的 Svelte 组件?

How can I create a Svelte component that uses properties from a nested component?

我正在尝试创建一个使用嵌套 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 道具。我该怎么做才能在 parent 组件中使用该道具? 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 组件没有导出 title 道具,它正在导出对 title 道具的控制。因此,在您的父组件 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 and here's the Svelte tutorial on Exporting props