Implement a portal in Svelte

梦想与她 提交于 2020-12-06 12:23:32

问题


In React you can render a component in a different node using Portals:

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

Same for Vue using the portal-vue package.

But is there a way to something similar in Svelte?

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

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

回答1:


See this issue : 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>

You can then you it with the following template. Modal will be renderer under <body/> :

<Portal>
  <Modal/>
</Portal>



回答2:


One solution would be to use the svelte-portal library:

​<script​>​
  ​import​ ​Portal​ ​from​ ​'svelte-portal'​;​
​</​script​>​

​<​Portal​ ​target​="​body"​>​
    <Modal/>
</​Portal​>​


来源:https://stackoverflow.com/questions/62733094/implement-a-portal-in-svelte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!