Svelte Modal 通过函数传递道具与 HTML

Svelte Modal Passing Props via Function vs. HTML

我有一个模态设置。模态通过 on:click.

触发

我可以很好地发送组件,它会呈现,但我想包含一个道具 (clientId)。

<script>
            
    //Modal code
    import Modal from "./Modal.svelte";
    import ClientNew from "./ClientNew";

    // initialise modal state and content
    let showModal = false;
    let modalContent;

    // pass in component as parameter and toggle modal state
    function toggleModal(component, clientId) {
        modalContent = component;
        showModal = !showModal;
    }
</script>

{#if showModal}
    <Modal on:click="{toggleModal}" modalContent="{modalContent}" />
{/if}

<div
    class="button secondary medium add-contact"
    on:click="{() => toggleModal(ClientNew, 12345)}">
    Add Client
</div>

我希望 clientId 成为在模态中呈现的 ClientNew 组件的道具。

我建议在 Modal

中使用 svelte:component 标签
<script>
        
        //Modal code
        import Modal from "./Modal.svelte";
        import ClientNew from "./ClientNew";
        
        // initialise modal state and content
        let showModal = false;
        let modalContent;
        let modalProps = {} /*added this */
        // pass in component as parameter and toggle modal state
        function toggleModal(component, props) { /*modified props */
          modalContent = component;
          modalProps = props /* added this */
          showModal = !showModal;
        }
        </script>

        {#if showModal}
          <!-- added modalProps -->
          <Modal on:click="{toggleModal}" {modalProps} {modalContent} />
        {/if}

        <div
          class="button secondary medium add-contact"
          on:click="{() => toggleModal(ClientNew, {clientid: 12345})}">
          Add Client
        </div>
<!-- inside Modal.svelte-->
<script>
  export let modalContent;
  export let modalProps;
</script>
<!--other markup if you have -->
{#if modalContent}
  <svelte:component this={modalContent}  {modalProps}/>
{/if}

现在在里面 clientNew.svelte (modalContet)

<script>
  /*now you can use clientid in clientNew.svelte */
  export let modalProps
</script>

{#if modalProps.clientid}
  <div>{modalProps.clientid}<div/>
{/if}