【问题标题】:How to use modal in svelte如何在 svelte 中使用模态
【发布时间】:2021-05-13 08:08:19
【问题描述】:

你好,当我尝试做一些苗条的模态时,我遇到了一个错误。

这是 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>

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

<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.

有什么想法吗?

【问题讨论】:

  • getContext('simple-modal') 里面有什么?我几乎可以肯定你那里没有物体。

标签: html css modal-dialog svelte


【解决方案1】:

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

<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>

您看到的异常是由不是&lt;Modal&gt; 子级的&lt;Podcast&gt; 组件引发的,因此未设置simple-modal 上下文。

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 2019-11-15
    • 2019-11-13
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多