Portal
提供了一種將子節點渲染到存在於父組件以外的 DOM 節點的優秀的方案。比如,在某個場景下,父組件的 overflow: hidden
或 z-index
屬性被設置時,會影響子元素,假如我們不希望這樣,這是我們就可以選用 Portal
,讓子元素跳出父元素的圈圈。常用的場景有:Modal 模態框
、Popover 彈出
Drawer抽屜
等。
這樣一來,我們現在組件的結構可以像這樣:
<html>
<body>
<div id="app"></div>
<div id="modal"></div>
<div id="gotop"></div>
<div id="alert"></div>
</body>
</html>
編寫組件代碼,保證模態框被單例掛載到 id=modal
的節點上
const modalRoot = document.getElementById('modal');
class Modal extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement('div');
}
componentDidMount() {
modalRoot.appendChild(this.el);
}
componentWillUnmount() {
modalRoot.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(
this.props.children,
this.el,
);
}
}
如此一來,Modal
組件的掛載節點就不用跟隨父節點了,Portal
允許我們根據需求任意地掛載節點。