Svelte 道具不会传递到插槽

问题描述 投票:0回答:1

我有一个带有槽的组件,我想将道具传递给它。然而,虽然我 can 将变量从父级直接传递到插槽,但由于某些原因直接从具有插槽的组件传递它不起作用。这是REPL.

代码:

<!-- App.svelte -->
<script>
    import Action from "./Action.svelte"
    import Icon from "./Icon.svelte"
    let size = 50;
</script>

<Action id="Home" isActive={true}>
  <Icon {size}/> <!-- works -->
</Action>
<!-- Action.svelte -->
<script>
    import { createEventDispatcher } from "svelte";
    const dispatch = createEventDispatcher();

    export let isActive = false;
    export let id = "unassigned";
    let size = 12;
    let strokeColor = "#f00";
    let fillColor= "#0f0";
    let fontColor = "#333";

    const enter = () => {
        if (isActive) {
            strokeColor = "#ccc";
            fillColor = "#999";
        }
    };

    const leave = () => {
        strokeColor = "#00f";
        fillColor = "#16e";
    };
</script>

<div on:mouseenter={enter} on:mouseleave={leave}>
    <slot strokeColor={strokeColor} fillColor={fillColor} test={id}/> <!-- does NOT work -->
    <div>action: {size}-{id}-{strokeColor}-{fillColor}</div>
</div>
<!-- Icon.svelte -->
<script lang="ts">
  export let size = 24;
  export let strokeColor = "#00f";
  export let fillColor = "#0f0";
  export let test = "def";

</script>

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" height={size} width={size}
  ><path
    d="M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3zm6 15h-2v-6H9v6H7v-7.81l5-4.5 5 4.5V18z"
    fill={strokeColor} /><path
    d="M7 10.19V18h2v-6h6v6h2v-7.81l-5-4.5y"
    fill={fillColor} /></svg>
<div>
icon: {size}, {strokeColor}, {fillColor}, {test}    
</div>

{size}
被正确传递到插槽,而所有其他来自
Action.svelte
的都被忽略:

<slot strokeColor={strokeColor} fillColor={fillColor} test={id}/>

任何帮助将不胜感激!

components parameter-passing svelte
1个回答
0
投票

这不是插槽属性的工作方式;插槽可以包含任何内容,并且值不会自动传递给任何和所有内容。

您必须使用

let:...
手动声明插槽属性并传递它们:

<Action id="Home" isActive={true}
        let:strokeColor let:fillColor let:test>
  <Icon {size} {strokeColor} {fillColor} {test} />
</Action>

文件

© www.soinside.com 2019 - 2024. All rights reserved.