【问题标题】:Implement a portal in Svelte在 Svelte 中实现门户
【发布时间】:2020-10-25 05:19:47
【问题描述】:

在 React 中,您可以使用 Portals 在不同的节点中渲染组件:

ReactDOM.createPortal( 
  <Component />,
  document.getElementById('id')
);

使用 portal-vue 包的 Vue 也是如此。

但是在 Svelte 中是否有类似的方法?

<body>
  <Header>
    <Modal /> <!-- Modal is rendered here -->
  </Header>

<!-- But the Modal DOM would be injected at the body end -->
</body>

【问题讨论】:

  • 仅供参考 这个问题的一般答案是只使用 DOM 方法,就像没有任何框架一样。由于 Svelte 不使用虚拟 DOM(与 React 或 Vue 不同),因此您实际上并不需要“门户”:)

标签: javascript svelte


【解决方案1】:

另一种解决方案是使用svelte-portal 库:

​<script​>​
  ​import​ ​Portal​ ​from​ ​'svelte-portal'​;​
​</​script​>​

​<​Portal​ ​target​="​body"​>​
    <Modal/>
</​Portal​>​

【讨论】:

    【解决方案2】:

    看到这个问题:https://github.com/sveltejs/svelte/issues/3088

    Portal.svelte

    <script>
    import { onMount, onDestroy } from 'svelte'
    let ref
    let portal
    
    onMount(() => {
      portal = document.createElement('div')
      portal.className = 'portal'
      document.body.appendChild(portal)
      portal.appendChild(ref)
    })
    
    onDestroy(() => {
      document.body.removeChild(portal)
    })
    
    </script>
    
    <div class="portal-clone">
      <div bind:this={ref}>
        <slot></slot>
      </div>
    </div>
    <style>
      .portal-clone { display: none; }
    </style>
    

    然后您可以使用以下模板。 Modal 将在&lt;body/&gt; 下渲染:

    <Portal>
      <Modal/>
    </Portal>
    

    【讨论】:

    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 2011-01-20
    • 2021-08-01
    • 2016-11-12
    • 2020-12-09
    相关资源
    最近更新 更多