import React, { Component } from 'react' import PropTypes from 'prop-types' import assign from 'object-assign' import _ from 'lodash' import { observable, action, } from 'mobx' import { observer, } from 'mobx-react' import uuidv1 from 'uuid/v1' import './index.less' const popupComps = observable.object({ size: 0, }, {}, { deep: false }) window.popupComps = popupComps @observer class PopUpLayer extends Component { static add = action((comp, mode = 'gray') => { // mode 可选值为 gray 或 transparent console.log('add comp ', comp, React.isValidElement(comp)) if (React.isValidElement(comp)) { const key = uuidv1() const containerStyle = {} if (mode === 'transparent') { containerStyle.backgroundColor = 'rgba(0, 0, 0, 0)' } popupComps[key] = ({ React.cloneElement(comp, { onClose: _.flow(comp.props.onClose || _.noop, () => { PopUpLayer.remove(key) }), }) }) popupComps.size += 1 return key } return null }) static remove = action((key) => { const comp = popupComps[key] if (_.isNil(comp) === false) { delete popupComps[key] popupComps.size -= 1 } }) static propTypes = { style: PropTypes.object, } static defaultProps = { style: {}, } componentDidMount() { } componentWillUnmount() { } timeOutFlag render() { const wrapStyles = assign({}, this.props.style, { visibility: popupComps.size > 0 ? 'visible' : 'hidden', }) return ({ _.map(_.values(popupComps), (comp, i) => { return React.isValidElement(comp) ? ( React.cloneElement(comp, { style: _.assign(comp.props.style, { zIndex: i, }), }) ) : null }) }) } } export default PopUpLayer
.popup-layer-wrap { position: absolute; top:0; left: 0; width: 100%; height: 100%; z-index: 10000; .popup-component-wrap { position: absolute; top:0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; flex-direction: column; justify-content: center; align-items: center; } }