在 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)
看到这个问题: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)
归档时间: |
|
查看次数: |
798 次 |
最近记录: |