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
相关产品推荐
相关产品推荐

