createPortal
允许你将 JSX 作为 children 渲染至 DOM 的不同部分。
createPortal(children, domNode, key?)
使用 portal 渲染模态对话框
import NoPortalExample from "./components/NoPortalExample";
import PortalExample from "./components/PortalExample";
function App() {
return (
<div className="App">
<div className="clipping-container">
<NoPortalExample />
</div>
<div className="clipping-container">
<PortalExample />
</div>
</div>
);
}
export default App;
import React from 'react';
function ModalContent({ onClose }) {
return (
<div>
<div>这是一个对话模态框</div>
<button onClick={onClose}>关闭</button>
</div>
);
}
export default ModalContent;
import React, {useState} from 'react';
import ModalContent from "./ModalContent";
function NoPortalExample(props) {
const [showModal, setShowModal] = useState(false)
return (
<div>
<button onClick={() => setShowModal(true)}>不使用 portal 展示模态</button>
{showModal && (
<ModalContent onClose={() => setShowModal(false)} />
)}
</div>
);
}
export default NoPortalExample;
import React, {useState} from 'react';
import ModalContent from "./ModalContent";
import {createPortal} from "react-dom";
function PortalExample(props) {
const [showModal, setShowModal] = useState(false);
return (
<div>
<button onClick={() => setShowModal(true)}>使用 portal 展示模态</button>
{showModal && createPortal(
<ModalContent onClose={() => setShowModal(false)} />,
document.body
)}
</div>
);
}
export default PortalExample;