Portal 提供了一种将子节点渲染到存在于父组件以外的 DOM 节点的优秀的方案。常见场景:对话框、悬浮卡以及提示框!
定义一个 模态框组件:
1import React, { 2 useRef, 3 useEffect, 4} from 'react'; 5import ReactDOM from 'react-dom'; 6 7const Modal = () => { 8 const elRef = useRef<HTMLDivElement>(document.createElement('div')); 9 10 useEffect(() => { 11 document.body.appendChild(elRef.current); 12 return () => { 13 elRef.current && document.body.removeChild(elRef.current); 14 }; 15 }, []); 16 17 if (!elRef.current) { 18 return null; 19 } 20 21 return ReactDOM.createPortal(<div>这个是模态框,直接挂载在body下面!!</div>, elRef.current); 22};
在另一个组件中使用该模态框组件:
1const App: React.FC = memo(() => { 2 const [portalVisible, setPortalVisible] = useState(false); 3 4 return ( 5 <div> 6 <button type="button" onClick={() => setPortalVisible(!portalVisible)}> 7 测试Portal 8 </button> 9 {portalVisible && <Modal />} 10 </div> 11 ); 12});