如何在 svelte 中使用模态

How to use modal in svelte

你好,当我尝试做一些 svelte modal 时出现错误。

这是 App.svelte 的代码:

<script>
    import Podcast from "./components/Podcast.svelte";
    import Modal from 'svelte-simple-modal';
</script>

<style>

</style>

<main>
    <Modal>
        <Podcast color={"red"} title={"red"} />
    </Modal>
    <Podcast color={"green"} title={"green"} />
    <Podcast color={"blue"} title={"blue"} />
    <Podcast color={"purple"} title={"purple"} />
    <Podcast color={"yellow"} title={"yellow"} />
    <Podcast color={"brown"} title={"brown"} />
    <Podcast color={"orange"} title={"orange"} />
</main>

这是我要处理点击的播客组件:

<script>
    import { getContext } from 'svelte';
    import ModalContent from './ModalContent.svelte';

    export let title;
    export let color;
    
    const { open } = getContext('simple-modal');
  
    const showModal= () => {
      open(ModalContent);
    };
</script>

<style>
    section
    {
        width: auto;
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>

<section on:click={showModal} style="background-color: {color}">
      The title is : &nbsp;
    <b> 
        {title} 
    </b>
</section>

这是我模态的内容(仅用于测试目的 rn):

<script>
    // your script goes here
</script>

<style>
    /* your styles go here */
</style>

test test

我有这个错误:

Uncaught TypeError: Cannot destructure property 'open' of 'getContext(...)' as it is undefined.

有什么想法吗?

上下文仅对设置上下文的组件 (tutorial chapter) 的子项可用。因此,<Modal> 需要包装您的整个应用程序。

<main>
    <Modal>
        <Podcast color={"green"} title={"green"} />
        <Podcast color={"blue"} title={"blue"} />
        <Podcast color={"purple"} title={"purple"} />
        <Podcast color={"yellow"} title={"yellow"} />
        <Podcast color={"brown"} title={"brown"} />
        <Podcast color={"orange"} title={"orange"} />
    </Modal>
</main>

您看到的异常是由 <Podcast> 不是 <Modal> 的子组件的组件抛出的,因此未设置 simple-modal 上下文。