在 Svelte 中实现门户 [英] Implement a portal in Svelte

查看:30
本文介绍了在 Svelte 中实现门户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React 中,您可以使用 Portals 在不同节点中渲染组件:

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

使用 portal-vue 包的 Vue 也是如此.

但是在 Svelte 中是否有类似的方法?

<标题><模态/><!-- 模态在此处呈现--></标题><!-- 但是 Modal DOM 会在 body 端注入 -->

解决方案

看到这个问题:https://github.com/sveltejs/svelte/issues/3088

Portal.svelte

<div class="portal-clone"><div bind:this={ref}><插槽></插槽>

<风格>.portal-clone { 显示:无;}</风格>

然后您可以使用以下模板.Modal 将成为 下的渲染器:

<模态/></门户>

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>

解决方案

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>

这篇关于在 Svelte 中实现门户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆