React在body下追加全局组件
import React from 'react'; import {createPortal} from 'react-dom'; export default class BodyPopupMask extends React.Component { constructor(props) { super(props); const doc = window.document; this.popupMaskNode = doc.createElement('div'); doc.body.appendChild(this.popupMaskNode); } render() { const { children, className = '' } = this.props return createPortal( <div className={`popup_content_mask ${className}`}> { children } </div>, //塞进传送门的JSX this.popupMaskNode //传送门的另一端DOM popupMaskNode ); } componentWillUnmount() { //在组件从 DOM 中移除之前立刻被调用 window.document.body.removeChild(this.popupMaskNode); } } // import PopupMask from '@/components/BodyPopupMask/BodyPopupMask.jsx'; /* <PopupMask className=""> <div>内容</div> </PopupMask> */