React Portals 简述及其用例

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"React Portal是一种优秀的方法,可以将子组件渲染到由组件树层次结构定义的父DOM层次结构之外的DOM节点中。Portal的最常见用例是子组件需要从视觉上脱离父容器的情况,如下所示。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"模态对话框"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"工具提示"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"悬浮卡片"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"加载器"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"可以使用ReactDOM.createPortal(child, container)创建一个Portal。这里的"},{"type":"text","marks":[{"type":"strong"}],"text":"child"},{"type":"text","text":"是一个React元素、片段或字符串,而"},{"type":"text","marks":[{"type":"strong"}],"text":"container"},{"type":"text","text":"是Portal应该注入到的DOM位置(节点)。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"以下是使用上述API创建的一个示例模态(modal)组件。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"text"},"content":[{"type":"text","text":"const Modal =({ message, isOpen, onClose, children })=> {\n if (!isOpen) return null\n return ReactDOM.createPortal( \n
\n {message}\n