Portal
编辑此页面<Portal>
可以将元素放在文档中的不同位置:
import { Portal } from "solid-js/web";
<Portal> <div class="popup">...</div></Portal>;
嵌套在 <Portal>
中的内容默认渲染在文档 body 的末尾。
位置可以通过传递给 <Portal>
的 mount
属性来更改。mount
属性接收一个 DOM 节点,该节点将用作 Portal 内容的挂载点。
import { Portal } from "solid-js/web";
<Portal mount={document.querySelector("main")}> <div class="popup">...</div></Portal>;
当元素(例如信息弹出窗口)由于父元素的溢出设置而被剪切或遮挡时,使用 <Portal>
特别有用。通过将该元素放在父元素之外,它就不再受其父元素的溢出设置的约束。这为用户创造了更易于访问的体验,因为内容不再复杂。
Info:
<Portal>
渲染的时候将会包一层元素,除非专门针对 document.head
。
这样事件就可以根据组件层次结构而非元素层次结构进行传播。
默认情况下,子级将包裹在 <div>
中。但如果您要放入 SVG 中,则必须使用 isSVG
prop 来避免将子项包在 <div>
中,此时将转为包在 <g>
中。
import { Portal } from "solid-js/web";
function Rect() { return ( <Portal mount={document.querySelector("svg")} isSVG={true}> <rect fill="red" x="25" y="25" height="50" width="50" /> </Portal> );}
function SVG() { return <svg xmlns="http://www.w3.org/2000/svg" />;}