可动态增加、删除的全局蒙灰弹层

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] = (
        <div className="popup-component-wrap" key={key} style={containerStyle}>
          {
            React.cloneElement(comp, {
              onClose: _.flow(comp.props.onClose || _.noop, () => { PopUpLayer.remove(key) }),
            })
          }
        </div>
      )
      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 (
      <div className="popup-layer-wrap" style={wrapStyles}>
        {
          _.map(_.values(popupComps), (comp, i) => {
            return React.isValidElement(comp) ? (
              React.cloneElement(comp, {
                style: _.assign(comp.props.style, {
                  zIndex: i,
                }),
              })
            ) : null
          })
        }
      </div>
    )
  }
}

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;
  }
}

 

posted @ 2019-09-02 14:56  贝子涵夕  阅读(232)  评论(0)    收藏  举报