You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte 5+Runes:svelte:component弃用后动态组件实现方案咨询

Svelte 5 Runes 替代弃用的svelte:component实现动态组件

问题背景

迁移原有Svelte组件到Svelte 5的Runes语法时,原代码依赖的<svelte:component>已被弃用,需要找到无需编写大量if-else语句的动态组件实现方式,替代原this={}的写法。

原代码

<script lang="ts">
  import type { SpaceAmenities } from "$src/spaces.d";
  import {
    Computer,
    Plug,
    Printer,
    Box,
    Droplet,
    Wifi,
    CornerDownRight,
    Icon,
  } from "lucide-svelte/icons";

  interface Props {
    amenity: SpaceAmenities;
  }
  let { amenity, ...restProps }: Props = $props();

  const amenityMap: Record<SpaceAmenities, typeof Icon> = {
    Computers: Computer,
    Outlets: Plug,
    Printing: Printer,
    Rooms: Box,
    "Water Fountains": Droplet,
    WiFi: Wifi,
  };
</script>

<svelte:component
  this={amenityMap[amenity] ?? CornerDownRight}
  class="h-fit w-fit scale-75"
  {...restProps}
/>

解决方案

Svelte 5支持直接将组件赋值给变量,随后以变量作为组件标签渲染,完美替代<svelte:component>的功能,同时保留原有映射表逻辑,无需大量分支判断。

修改后的代码:

<script lang="ts">
  import type { SpaceAmenities } from "$src/spaces.d";
  import {
    Computer,
    Plug,
    Printer,
    Box,
    Droplet,
    Wifi,
    CornerDownRight,
    Icon,
  } from "lucide-svelte/icons";

  interface Props {
    amenity: SpaceAmenities;
  }
  // 使用Svelte 5 Runes语法的$props,指定属性类型
  const { amenity, ...restProps } = $props<Props>();

  const amenityMap: Record<SpaceAmenities, typeof Icon> = {
    Computers: Computer,
    Outlets: Plug,
    Printing: Printer,
    Rooms: Box,
    "Water Fountains": Droplet,
    WiFi: Wifi,
  };

  // 获取目标组件,不存在则使用默认组件
  const DynamicIcon = amenityMap[amenity] ?? CornerDownRight;
</script>

<!-- 直接使用变量作为组件标签渲染 -->
<DynamicIcon class="h-fit w-fit scale-75" {...restProps} />

关键说明

  • 保留原有的amenityMap映射逻辑,无需修改;
  • 通过变量存储动态组件,直接以变量名作为组件标签使用,语法更简洁;
  • 完全兼容原有的属性传递逻辑,restProps可以正常展开传递给动态组件。

内容的提问来源于stack exchange,提问作者Mahyar Mirrashed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 20:02:48