Portal簡介
所以我們需要的一個(gè)通用組件,它做如下的事情:
可以聲明式的寫在一個(gè)組件中 并不真正render在被聲明的地方 支持過渡動(dòng)畫那么,像modal、tooltip、notification等組件都是可以基于這個(gè)組件的。我們叫這個(gè)組件為Portal。
使用了React16+的你,對(duì)Portal至少有所了解或者熟練使用。
Portal可以創(chuàng)建一個(gè)在你的root元素之外的DOM。
1、通常你的網(wǎng)站只有一個(gè)root
<body> <div id="root"></div></body>
2、使用Portal之后,可以變成下面這樣
<body> <div id="root"></div> <div id="portal"></div></body>
Portal高階組件封裝
Portal的demo在官網(wǎng)上可以看到,而我們要實(shí)現(xiàn)的是將它封裝成一個(gè)可以復(fù)用的組件。
目標(biāo)
不需要手動(dòng)在body下面增加HTML,通過組件自己去創(chuàng)建。
<CreatePortal id, //可以傳入id className, //可以傳入className style //可以傳入style > 此處插入div或者react組件</CreatePortal>
實(shí)現(xiàn)方案
1、創(chuàng)建一個(gè)createPortal函數(shù),該函數(shù)將會(huì)return一個(gè)Portal組件
function createPortal() {}export default createPortal()2、創(chuàng)建Portal組件
import React from 'react'import ReactDOM from 'react-dom'import PropTypes from 'prop-types'function createPortal() { class Portal extends React.Component{ } return Portal}export default createPortal()3、render函數(shù)實(shí)現(xiàn),用createPortal創(chuàng)建portal。
render() { return ReactDOM.createPortal( this.props.children, this.el )}4、componentDidMount函數(shù)實(shí)現(xiàn),將dom添加到body下面
componentDidMount() { document.body.appendChild(this.el);}5、componentWillUnmount函數(shù)實(shí)現(xiàn),清除DOM結(jié)構(gòu)
componentWillUnmount() { document.body.removeChild(this.el) }6、實(shí)現(xiàn)props,包括id、className、style
constructor(props) { super(props) this.el = document.createElement('div') if (!!props) { this.el.id = props.id || false if (props.className) this.el.className = props.className if (props.style) { Object.keys(props.style).map((v) => { this.el.style[v] = props.style[v] }) } document.body.appendChild(this.el) }}7、完整代碼
import React from 'react'import ReactDOM from 'react-dom'import PropTypes from 'prop-types'function createPortal() { class Portal extends React.Component{ constructor(props) { super(props) this.el = document.createElement('div') if (!!props) { this.el.id = props.id || false if (props.className) this.el.className = props.className if (props.style) { Object.keys(props.style).map((v) => { this.el.style[v] = props.style[v] }) } document.body.appendChild(this.el) } } componentDidMount() { document.body.appendChild(this.el); } componentWillUnmount() { document.body.removeChild(this.el) } render() { return ReactDOM.createPortal( this.props.children, this.el ) } } Portal.propTypes = { style: PropTypes.object } return Portal}export default createPortal()
新聞熱點(diǎn)
疑難解答
圖片精選