Portal簡(jiǎn)介
所以我們需要的一個(gè)通用組件,它做如下的事情:
那么,像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,通過(guò)組件自己去創(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()總結(jié)
createPortal和Provide實(shí)現(xiàn)思想類似,用函數(shù)式編程的思想來(lái)完成目標(biāo)。如果你覺(jué)得這東西有用,拿去用吧。
好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注