Portals
React 16的Portals特性讓我們可以把組件渲染到當(dāng)前組件樹(shù)以外的 DOM節(jié)點(diǎn)上宰掉,這個(gè)特性典型的應(yīng)用場(chǎng)景是渲染應(yīng)用的全局彈框,使用 Portals后,任意組件都可以將彈框組件渲染到根節(jié)點(diǎn)上,以方便彈框的 顯示渗钉。Portals的實(shí)現(xiàn)依賴(lài)ReactDOM的一個(gè)新的API:
ReactDOM.createPortal(child, container)
第一個(gè)參數(shù)child是可以被渲染的React節(jié)點(diǎn),例如React元素钞钙、由 React元素組成的數(shù)組鳄橘、字符串等,container是一個(gè)DOM元素芒炼,child將 被掛載到這個(gè)DOM節(jié)點(diǎn)瘫怜。
普通情況下,組件的render函數(shù)返回的元素會(huì)被掛載在它的父級(jí)組件上焕议。
然而宝磨,有些元素需要被掛載在更高層級(jí)的位置弧关。最典型的應(yīng)用場(chǎng)景:當(dāng)父組件具有overflow: hidden
或者z-index
的樣式設(shè)置時(shí)盅安,組件有可能被其他元素遮擋,這個(gè)時(shí)候你就可以考慮要不要使用Portal使組件的掛載脫離父組件世囊。例如:對(duì)話(huà)框别瞭,tooltip。
class Modal extends Component {
? constructor(props) {
? super(props);
? this.container = document.createElement('div');
? document.body.appendChild(this.container);
? }
? componentWillUnmount(){
? document.body.removeChild(this.container);
? console.log("Unmount");
?
? }
? render() {
? return ReactDom.createPortal(
<div className ="modals">
? { <span className="close" onClick={this.props.onClose}> × </span> }
? { <div className="content"> {this.props.children}</div>}
? </div>
?
? , this.container);
? }
}
在APP.js 中調(diào)用
class App extends Component {
constructor(props) {
super(props);
this.state = { showModal: true };
}
// 關(guān)閉彈框
closeModal = () => {
this.setState({ showModal: false });
};
render() {
return (
<div>
<h2>Dashboard</h2>
{this.state.showModal && (<Modal onClose={this.closeModal }>modal dialog</Modal>)}
</div>
);
}
}
1554007649593.png