[英]Implement a portal in Svelte
在 React 中,您可以使用Portals在不同的节点中渲染组件:
ReactDOM.createPortal(
<Component />,
document.getElementById('id')
);
Vue 使用portal-vue package 也是如此。
但是在 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.