在 Svelte 中实施门户

2024-03-08

在 React 中,你可以使用以下命令在不同的节点中渲染组件Portals https://reactjs.org/docs/portals.html:

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

对于 Vue 来说也是如此,使用门户Vue https://github.com/LinusBorg/portal-vue包裹。

但是 Svelte 中有没有类似的方法呢?

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

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

请参阅此问题:https://github.com/sveltejs/svelte/issues/3088 https://github.com/sveltejs/svelte/issues/3088

门户网站.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>

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

<Portal>
  <Modal/>
</Portal>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Svelte 中实施门户 的相关文章

随机推荐