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

Svelte 5中如何直接访问组件传入的子组件?

Svelte 5中直接访问组件子元素的实现方案

在Svelte 5项目里,若通过$props()获取到组件的children后,不想使用{@render children()},而是直接访问传入的子组件及其props,可按以下方式修改代码:

修改后的Gallery组件代码:

<script>
  import Image from "./Image.svelte";

  let { children } = $props();    
  // 执行children函数拿到子组件数组
  const childComponents = children();
</script>

<p>The gallery contains {childComponents.length} images</p>

<p>The first image is {childComponents[0].props.url} </p>

核心逻辑说明:

  • 在Svelte 5中,children是一个返回子元素数组的函数,必须执行children()才能获取实际的子组件列表,用childComponents.length即可获取传入的图片数量(对应原代码中的{???})
  • 数组里的每个子元素对象包含props属性,存储了传入该子组件的所有参数,因此通过childComponents[0].props.url就能直接拿到第一个Image组件的url值(对应原代码中的{????})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 14:12:33