index.js 1.94 KB
Newer Older
xuzhenghua committed
1 2 3 4 5
import React from 'react'
import ReactDOM from 'react-dom'
import './index.scss'
import classnames from 'classnames'

zhanghaozhe committed
6 7
const re = /(https?|ftp):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/

xuzhenghua committed
8
function ClosablePopup({
zhanghaozhe committed
9 10 11 12 13 14
                         title,
                         content,
                         className,
                         closable = true,
                         close = function () {
                         },
zhanghaozhe committed
15
                         clickMaskClose = true,
zhanghaozhe committed
16 17 18 19 20 21
                         closeIcon = 'iconiconfront-2',
                         afterClose = function () {
                         },
                         remove = function () {

                         }
xuzhenghua committed
22 23
                       } = {}) {

zhanghaozhe committed
24

xuzhenghua committed
25 26 27 28 29 30 31 32 33 34 35 36
  function unmountComponent() {
    ReactDOM.unmountComponentAtNode(div)
    if (div && div.parentNode) {
      div.parentNode.removeChild(div)
    }
  }

  function _close() {
    let _c = close()
    if (_c && _c.then) {
      _c.then(() => {
        unmountComponent()
zhanghaozhe committed
37
        afterClose()
xuzhenghua committed
38 39 40
      })
    } else {
      unmountComponent()
zhanghaozhe committed
41
      afterClose()
xuzhenghua committed
42 43 44
    }
  }

zhanghaozhe committed
45
  function clickMask() {
zhanghaozhe committed
46
    if (closable) {
zhanghaozhe committed
47 48
      return
    }
zhanghaozhe committed
49
    if (!clickMaskClose) {
zhanghaozhe committed
50 51 52 53
      return
    }
    _close()
  }
xuzhenghua committed
54 55

  const closablePopup = (
zhanghaozhe committed
56
    <div className={'closable-popup-mask'} onClick={clickMask}>
xuzhenghua committed
57 58 59 60 61 62
      <div className={classnames(['popup-container', className])}>
        <div className="title">{title}</div>
        <div className="content">
          {content}
        </div>
        {
zhanghaozhe committed
63
          closable &&
zhanghaozhe committed
64
          (re.test(closeIcon)
zhanghaozhe committed
65
            ? <img src={closeIcon} alt="" className={'close-icon'} onClick={_close}/>
zhanghaozhe committed
66
            : <i className={`close iconfont ${closeIcon}`} onClick={_close}/>)
xuzhenghua committed
67 68 69 70 71 72 73 74 75 76 77
        }
      </div>
    </div>
  )
  const div = document.createElement('div')
  document.body.appendChild(div)


  ReactDOM.render(closablePopup, div)

  return {
zhanghaozhe committed
78 79
    close: _close,
    remove: unmountComponent
xuzhenghua committed
80 81 82 83
  }
}

export default ClosablePopup