[英]How to inherit slots with svelte components?
有一個組件<Bar>
繼承自組件<Foo>
。
<Foo>
組件定義了一個名為content
的插槽,其中包含一個備用內容。 <Bar>
組件還定義了一個名為content
的插槽,其中包含不同的備用內容。
<!-- Foo.svelte -->
<slot name="content">
foo fallback
</slot>
<!-- Bar.svelte -->
<script>import Foo from './Foo.svelte'</script>
<Foo>
<span slot="content">
bar fallback
</span>
</Foo>
<Bar>
組件在使用<Foo/>
調用時顯示回退,但在使用<Bar><span slot="content">bar custom</span></Bar>
調用時不顯示自定義內容。
你能告訴我我做錯了什么嗎?
<Foo/>
<!-- prints 'foo fallback': OK -->
<Foo>
<span slot="content">foo custom</span>
</Foo>
<!-- prints 'foo custom': OK -->
<Bar/>
<!-- prints 'bar fallback': OK -->
<Bar>
<span slot="content">bar custom</span>
</Bar>
<!-- prints 'bar fallback': KO - I would have expected 'bar custom' -->
請注意,此代碼過於簡單,我的實際用例比這要復雜一些,我需要在那里使用插槽。
小提琴: https://svelte.dev/repl/5c525651eb8b4f60a6a696c1bd19f723
看起來您想在Foo
定義的插槽中呈現傳遞給Bar
的插槽內容,但目前您尚未在Bar
中定義插槽,因此無處可使用傳遞的內容,因此后備值始終傳遞給Foo
。
解決方案可能如下所示,在傳遞給Foo
的內容槽的跨度內的Bar
中定義一個content
槽。
// App.svelte
<script>
import Foo from './Foo.svelte'
import Bar from './Bar.svelte'
</script>
Expected: <em>bar custom</em><br>
<Bar>
<span slot="content">bar custom</span>
</Bar>
// ./Bar.svelte
<script>
import Foo from './Foo.svelte';
</script>
<Foo>
<span slot="content">
<slot name="content">bar fallback</slot>
</span>
</Foo>
// ./Foo.svelte
<slot name="content">
foo fallback
</slot>
我認為大多數答案都非常接近。 我相信您可以通過創建一個內容和名稱都具有相同值的插槽來修復它。 以您的示例為基礎( Repl 具有完整的第 3 級 inheritance ),
<!-- Foo.svelte -->
<slot name="content">
foo fallback
</slot>
<!-- Bar.svelte -->
<script>import Foo from './Foo.svelte'</script>
<Foo>
<slot name="content" slot="content">
bar fallback
</slot>
</Foo>
通過這種方式,我們既可以通過插槽,也可以包含我們的新后備。
如果您想確保跨度在那里,可以根據您的用例將其放在slot
內部或外部來完成。
<!-- Bar.svelte -->
<script>import Foo from './Foo.svelte'</script>
<!-- option 1-->
<Foo>
<span>
<slot name="content" slot="content">
bar fallback
</slot>
</span>
</Foo>
<!-- option 2-->
<Foo>
<slot name="content" slot="content">
<span>
bar fallback
</span>
</slot>
</Foo>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.