[英]Implement a portal in Svelte
In React you can render a component in a different node using Portals :在 React 中,您可以使用Portals在不同的节点中渲染组件:
ReactDOM.createPortal(
<Component />,
document.getElementById('id')
);
Same for Vue using the portal-vue package. Vue 使用portal-vue package 也是如此。
But is there a way to something similar in Svelte?但是在 Svelte 中是否有类似的方法?
<body>
<Header>
<Modal /> <!-- Modal is rendered here -->
</Header>
<!-- But the Modal DOM would be injected at the body end -->
</body>
See this issue: https://github.com/sveltejs/svelte/issues/3088看到这个问题: https://github.com/sveltejs/svelte/issues/3088
Portal.svelte 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>
You can then you it with the following template.然后,您可以使用以下模板。 Modal will be renderer under <body/>
: Modal 将是<body/>
下的渲染器:
<Portal>
<Modal/>
</Portal>
Another solution would be to use the svelte-portal library:另一种解决方案是使用svelte-portal库:
<script>
import Portal from 'svelte-portal';
</script>
<Portal target="body">
<Modal/>
</Portal>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.