在 Svelte 中实现门户
Implement a portal in Svelte
在 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>
看到这个问题: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 将在 <body/>
下渲染:
<Portal>
<Modal/>
</Portal>
另一种解决方案是使用 svelte-portal 库:
<script>
import Portal from 'svelte-portal';
</script>
<Portal target="body">
<Modal/>
</Portal>
在 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>
看到这个问题: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 将在 <body/>
下渲染:
<Portal>
<Modal/>
</Portal>
另一种解决方案是使用 svelte-portal 库:
<script>
import Portal from 'svelte-portal';
</script>
<Portal target="body">
<Modal/>
</Portal>