在 Svelte 中实现门户

joh*_*pin 3 javascript svelte

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

ReactDOM.createPortal( 
  <Component />,
  document.getElementById('id')
);
Run Code Online (Sandbox Code Playgroud)

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

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

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

<!-- But the Modal DOM would be injected at the body end -->
</body>
Run Code Online (Sandbox Code Playgroud)

Jér*_*e B 6

看到这个问题: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>
Run Code Online (Sandbox Code Playgroud)

然后您可以使用以下模板。模态将在以下渲染器<body/>

<Portal>
  <Modal/>
</Portal>
Run Code Online (Sandbox Code Playgroud)

  • 这些示例使用 Svelte 操作,这是另一种不需要组件但增强现有组件的方法: - https://svelte.dev/repl/86ec36c27be2471f86590e0c18c7198c?version=3.23.2 - https://svelte.dev/repl/ 79e33c2d7695444b994ba74255bb1387?版本=3.24.0 (4认同)