Svelte中命名插槽的Props传递与使用问题求助
Svelte命名插槽Slot Props使用问题解决
错误原因
你错误地将let:指令用在了<Navbar>组件标签上,而根据Svelte规则,命名插槽的Props必须在指定slot的元素(如<svelte:fragment>或带slot属性的标签)上使用let:,不能直接作用于父组件本身。
修正后的代码
首先修正Navbar.svelte里的笔误(你导入了Trail组件,但插槽里写的{Item}会导致未定义错误):
// $lib/components/Navbar.svelte import Lead from './Lead.svelte' import Trail from './Trail.svelte' <nav> <slot name="lead" {Lead}>(lead)</slot> <ul> <!-- 把{Item}改为{Trail} --> <slot name="trail" {Trail}>(trail)</slot> </ul> </nav>
然后修正组件使用代码,将let:Lead移到<svelte:fragment>上:
// 使用组件 import Navbar from '$lib/components/Navbar.svelte' <Navbar> <!-- 在带slot属性的元素上使用let:接收插槽Props --> <svelte:fragment slot="lead" let:Lead> <Lead {my_props}> <span>More</span> </Lead> </svelte:fragment> </Navbar>
核心规则回顾
Svelte官方明确要求:
Named slots can also have props; use the let directive on an element with a slot="..." attribute, instead of on the component itself.
简单来说,命名插槽的Props传递和接收是绑定到具体slot元素的,而非父组件容器。
内容的提问来源于stack exchange,提问作者Nguyễn Anh Tuấn
相关产品推荐
相关产品推荐

