React网页自定义弹层组件RLayer|react.js弹窗组件

基于React.js自定义PC端对话框组件RLayer

RLayer 一款基于react.js开发的桌面端自定义交互式弹框组件。拥有丰富的接口及漂亮的皮肤。支持Alert、Dialog、Message、Notification、ActionSheet、Toast、Popover、Popconfirm等弹窗类型。

RLayer.js组件在设计开发时有参考之前开发的VLayer组件。在功能及效果上保持一致。

vue pc端弹框组件,可以去看看这篇文章。

https://blog.csdn.net/yanxinyun1990/article/details/109447381

  • 12+弹框类型 [ toast、footer、actionsheet|actionsheetPicker、android|ios、contextmenu、drawer、iframe、message|notify|popover ]
  • 7+动画效果 [ scaleIn | fadeIn | footer | fadeInUp | fadeInDown | fadeInLeft | fadeInRight ]

引入

在相应页面引入rlayer.js组件。

// 引入组件RLayer
import rlayer from './components/rlayer';

提供极简的调用方式 rlayer({...})

const showDialog = () => {
    let $el = rlayer({
        title: '标题',
        content: "<div style='color:#0070f3;padding:30px;'>弹窗内容信息。</div>",
        shadeClose: true,
        zIndex: 2020,
        lockScroll: true,
        resize: false,
        dragOut: true,
        btns: [
            {
                text: '关闭',
                click: () => {
                    $el.close()
                }
            },
            {
                text: '确定',
                style: {color: '#09f'},
                click: () => {
                    // ...
                }
            }
        ]
    })
}

另外,当弹窗类型为 message、notify、popover,需通过如下调用方式。

rlayer.message({...});
rlayer.notify({...});
rlayer.popover({...});

效果预览

开发实现

rlayer.js支持超过30+个参数配置。

/**
 * 弹出框默认配置
 */
static defaultProps = {
    // 参数
    id: '',                       // {string} 控制弹层唯一标识,相同id共享一个实例
    title: '',                    // {string} 标题
    content: '',                  // {string|element} 内容(支持字符串或组件)
    type: '',                     // {string} 弹框类型(toast|footer|actionsheet|actionsheetPicker|android|ios|contextmenu|drawer|iframe)
    layerStyle: '',               // {object} 自定义弹框样式
    icon: '',                     // {string} Toast图标(loading|success|fail)
    shade: true,                  // {bool} 是否显示遮罩层
    shadeClose: true,             // {bool} 是否点击遮罩层关闭弹框
    lockScroll: true,             // {bool} 是否弹框显示时将body滚动锁定
    opacity: '',                  // {number|string} 遮罩层透明度
    xclose: true,                 // {bool} 是否显示关闭图标
    xposition: 'right',           // {string} 关闭图标位置(top|right|bottom|left)
    xcolor: '#333',               // {string} 关闭图标颜色
    anim: 'scaleIn',              // {string} 弹框动画(scaleIn|fadeIn|footer|fadeInUp|fadeInDown|fadeInLeft|fadeInRight)
    position: 'auto',             // {string|array} 弹框位置(auto|['150px','100px']|t|r|b|l|lt|rt|lb|rb)
    drawer: '',                   // {string} 抽屉弹框(top|right|bottom|left)
    follow: null,                 // {string|array} 跟随定位弹框(支持.xxx #xxx 或 [e.clientX,e.clientY])
    time: 0,                      // {number} 弹框自动关闭秒数(1|2|3...)
    zIndex: 8090,                 // {number} 弹框层叠
    topmost: false,               // {bool} 是否置顶当前弹框
    area: 'auto',                 // {string|array} 弹框宽高(auto|'250px'|['','200px']|['650px','300px'])
    maxWidth: 375,                // {number} 弹框最大宽度(只有当area:'auto'时设定才有效)
    maximize: false,              // {bool} 是否显示最大化按钮
    fullscreen: false,            // {bool} 是否全屏弹框
    fixed: true,                  // {bool} 是否固定弹框
    drag: '.rlayer__wrap-tit',    // {string|bool} 拖拽元素(可自定义拖动元素drag:'#xxx' 禁止拖拽drag:false)
    dragOut: false,               // {bool} 是否允许拖拽到浏览器外
    lockAxis: null,               // {string} 限制拖拽方向可选: v 垂直、h 水平,默认不限制
    resize: false,                // {bool} 是否允许拉伸弹框
    btns: null,                   // {array} 弹框按钮(参数:text|style|disabled|click)

    // 事件
    success: null,                // {func} 层弹出后回调
    end: null,                    // {func} 层销毁后回调
}
render() {
    let opt = this.state

    return (
        <>
        <div className={domUtils.classNames('rui__layer', {'rui__layer-closed': opt.closeCls})} id={opt.id} style={{display: opt.opened?'block':'none'}}>
            {/* 遮罩 */}
            { opt.shade && <div className="rlayer__overlay" onClick={this.shadeClicked} style={{opacity: opt.opacity}}></div> }
            <div className={domUtils.classNames('rlayer__wrap', opt.anim&&'anim-'+opt.anim, opt.type&&'popui__'+opt.type)} style={{...opt.layerStyle}}>
            { opt.title && <div className='rlayer__wrap-tit' dangerouslySetInnerHTML={{__html: opt.title}}></div> }
            <div className='rlayer__wrap-cntbox'>
                { opt.content ? 
                <>
                    {
                    opt.type == 'iframe' ? 
                    (
                        <iframe scrolling='auto' allowtransparency='true' frameBorder='0' src={opt.content}></iframe>
                    )
                    : 
                    (opt.type == 'message' || opt.type == 'notify' || opt.type == 'popover') ? 
                    (
                        <div className='rlayer__wrap-cnt'>
                        { opt.icon && <i className={domUtils.classNames('rlayer-msg__icon', opt.icon)} dangerouslySetInnerHTML={{__html: opt.messageIcon[opt.icon]}}></i> }
                        <div className='rlayer-msg__group'>
                            { opt.title && <div className='rlayer-msg__title' dangerouslySetInnerHTML={{__html: opt.title}}></div> }
                            { typeof opt.content == 'string' ? 
                            <div className='rlayer-msg__content' dangerouslySetInnerHTML={{__html: opt.content}}></div>
                            :
                            <div className='rlayer-msg__content'>{opt.content}</div>
                            }
                        </div>
                        </div>
                    )
                    : 
                    (
                        typeof opt.content == 'string' ? 
                        (<div className='rlayer__wrap-cnt' dangerouslySetInnerHTML={{__html: opt.content}}></div>)
                        :
                        opt.content
                    )
                    }
                </>
                :
                null
                }
            </div>
            { opt.btns && <div className='rlayer__wrap-btns'>
                {
                    opt.btns.map((btn, index) => {
                        return <span className={domUtils.classNames('btn')} key={index} style={{...btn.style}} dangerouslySetInnerHTML={{__html: btn.text}}></span>
                    })
                }
                </div>
            }
            { opt.xclose && <span className={domUtils.classNames('rlayer__xclose')}></span> }
            { opt.maximize && <span className='rlayer__maximize'></span> }
            { opt.resize && <span className='rlayer__resize'></span> }
            </div>
            <div className='rlayer__dragfix'></div>
        </div>
        </>
    )
}
/**
 * @Desc     ReactJs|Next.js自定义弹窗组件RLayer
 * @Time     andy by 2020-12-04
 * @About    Q:282310962  wx:xy190310
 */
import React from 'react'
import ReactDOM from 'react-dom'

// 引入操作类
import domUtils from './utils/dom'

let $index = 0, $lockCount = 0, $timer = {}

class RLayerComponent extends React.Component {
    static defaultProps = {
        // ...
    }

    constructor(props) {
        super(props)
        this.state = {
            opened: false,
            closeCls: '',
            toastIcon: {
                // ...
            },
            messageIcon: {
                // ...
            },
            rlayerOpts: {},
            tipArrow: null,
        }

        this.closeTimer = null
    }

    componentDidMount() {
        window.addEventListener('resize', this.autopos, false)
    }
    componentWillUnmount() {
        window.removeEventListener('resize', this.autopos, false)
        clearTimeout(this.closeTimer)
    }

    /**
     * 打开弹框
     */
    open = (options) => {
        options.id = options.id || `rlayer-${domUtils.generateId()}`

        this.setState({
            ...this.props, ...options, opened: true,
        }, () => {
            const { success } = this.state
            typeof success === 'function' && success.call(this)

            this.auto()
            this.callback()
        })
    }

    /**
     * 关闭弹框
     */
    close = () => {
        const { opened, time, end, remove, rlayerOpts, action } = this.state
        if(!opened) return

        this.setState({ closeCls: true })
        clearTimeout(this.closeTimer)
        this.closeTimer = setTimeout(() => {
            this.setState({
                closeCls: false,
                opened: false,
            })
            if(rlayerOpts.lockScroll) {
                $lockCount--
                if(!$lockCount) {
                    document.body.style.paddingRight = ''
                    document.body.classList.remove('rc-overflow-hidden')
                }
            }
            if(time) {
                $index--
            }
            if(action == 'update') {
                document.body.style.paddingRight = ''
                document.body.classList.remove('rc-overflow-hidden')
            }
            rlayerOpts.isBodyOverflow && (document.body.style.overflow = '')
            remove()
            typeof end === 'function' && end.call(this)
        }, 200);
    }

    // 弹框位置
    auto = () => {
        // ...

        this.autopos()

        // 全屏弹框
        if(fullscreen) {
            this.full()
        }

        // 弹框拖拽|缩放
        this.move()
    }

    autopos = () => {
        const { opened, id, fixed, follow, position } = this.state
        if(!opened) return
        let oL, oT
        let dom = document.querySelector('#' + id)
        let rlayero = dom.querySelector('.rlayer__wrap')

        if(!fixed || follow) {
            rlayero.style.position = 'absolute'
        }

        let area = [domUtils.client('width'), domUtils.client('height'), rlayero.offsetWidth, rlayero.offsetHeight]

        oL = (area[0] - area[2]) / 2
        oT = (area[1] - area[3]) / 2

        if(follow) {
            this.offset()
        } else {
            typeof position === 'object' ? (
                oL = parseFloat(position[0]) || 0, oT = parseFloat(position[1]) || 0
            ) : (
                position == 't' ? oT = 0 : 
                position == 'r' ? oL = area[0] - area[2] : 
                position == 'b' ? oT = area[1] - area[3] : 
                position == 'l' ? oL = 0 : 
                position == 'lt' ? (oL = 0, oT = 0) : 
                position == 'rt' ? (oL = area[0] - area[2], oT = 0) : 
                position == 'lb' ? (oL = 0, oT = area[1] - area[3]) :
                position == 'rb' ? (oL = area[0] - area[2], oT = area[1] - area[3]) : 
                null
            )

            rlayero.style.left = parseFloat(fixed ? oL : domUtils.scroll('left') + oL) + 'px'
            rlayero.style.top = parseFloat(fixed ? oT : domUtils.scroll('top') + oT) + 'px'
        }
    }

    // 跟随元素定位
    offset = () => {
        const { id, follow } = this.state
        let oW, oH, pS
        let dom = document.querySelector('#' + id)
        let rlayero = dom.querySelector('.rlayer__wrap')

        oW = rlayero.offsetWidth
        oH = rlayero.offsetHeight
        pS = domUtils.getFollowRect(follow, oW, oH)

        rlayero.style.left = pS[0] + 'px'
        rlayero.style.top = pS[1] + 'px'
    }

    // 最大化弹框
    full = () => {
        // ...
    }

    // 恢复弹框
    restore = () => {
        // ...
    }

    // 拖拽|缩放弹框
    move = () => {
        // ...
    }

    // 事件处理
    callback = () => {
        const { time } = this.state
        // 倒计时关闭弹框
        if(time) {
            $index++
            // 防止重复计数
            if($timer[$index] != null) clearTimeout($timer[$index])
            $timer[$index] = setTimeout(() => {
                this.close()
            }, parseInt(time) * 1000);
        }
    }

    // 点击最大化按钮
    maximizeClicked = (e) => {
        let o = e.target
        if(o.classList.contains('maximized')) {
            // 恢复
            this.restore()
        } else {
            // 最大化
            this.full()
        }
    }

    // 点击遮罩层
    shadeClicked = () => {
        if(this.state.shadeClose) {
            this.close()
        }
    }

    // 按钮事件
    btnClicked = (index, e) => {
        let btn = this.state.btns[index]
        if(!btn.disabled) {
            typeof btn.click === 'function' && btn.click(e)
        }
    }

    render() {
        let opt = this.state
        return (
            <>
            <div className={domUtils.classNames('rui__layer', {'rui__layer-closed': opt.closeCls})} id={opt.id} style={{display: opt.opened?'block':'none'}}>
                { opt.shade && <div className="rlayer__overlay" onClick={this.shadeClicked} style={{opacity: opt.opacity}}></div> }
                <div className={domUtils.classNames('rlayer__wrap', opt.anim&&'anim-'+opt.anim, opt.type&&'popui__'+opt.type, opt.drawer&&'popui__drawer-'+opt.drawer, opt.xclose&&'rlayer-closable', opt.tipArrow)} style={{...opt.layerStyle}}>
                { opt.title && <div className='rlayer__wrap-tit' dangerouslySetInnerHTML={{__html: opt.title}}></div> }
                { opt.type == 'toast' && opt.icon ? <div className={domUtils.classNames('rlayer__toast-icon', 'rlayer__toast-'+opt.icon)} dangerouslySetInnerHTML={{__html: opt.toastIcon[opt.icon]}}></div> : null }
                <div className='rlayer__wrap-cntbox'>
                    { opt.content ? 
                    <>
                        {
                        opt.type == 'iframe' ? 
                        (
                            <iframe scrolling='auto' allowtransparency='true' frameBorder='0' src={opt.content}></iframe>
                        )
                        : 
                        (opt.type == 'message' || opt.type == 'notify' || opt.type == 'popover') ? 
                        (
                            <div className='rlayer__wrap-cnt'>
                            { opt.icon && <i className={domUtils.classNames('rlayer-msg__icon', opt.icon)} dangerouslySetInnerHTML={{__html: opt.messageIcon[opt.icon]}}></i> }
                            <div className='rlayer-msg__group'>
                                { opt.title && <div className='rlayer-msg__title' dangerouslySetInnerHTML={{__html: opt.title}}></div> }
                                { typeof opt.content == 'string' ? 
                                <div className='rlayer-msg__content' dangerouslySetInnerHTML={{__html: opt.content}}></div>
                                :
                                <div className='rlayer-msg__content'>{opt.content}</div>
                                }
                            </div>
                            </div>
                        )
                        : 
                        (
                            typeof opt.content == 'string' ? 
                            (<div className='rlayer__wrap-cnt' dangerouslySetInnerHTML={{__html: opt.content}}></div>)
                            :
                            opt.content
                        )
                        }
                    </>
                    :
                    null
                    }
                </div>
                {/* btns */}
                { opt.btns && <div className='rlayer__wrap-btns'>
                    {
                        opt.btns.map((btn, index) => {
                            return <span className={domUtils.classNames('btn')} key={index} style={{...btn.style}} dangerouslySetInnerHTML={{__html: btn.text}}></span>
                        })
                    }
                    </div>
                }
                { opt.xclose && <span className={domUtils.classNames('rlayer__xclose')} style={{color: opt.xcolor}}></span> }
                { opt.maximize && <span className='rlayer__maximize'></span> }
                { opt.resize && <span className='rlayer__resize'></span> }
                </div>
                <div className='rlayer__dragfix'></div>
            </div>
            </>
        )
    }
}

react.js中动态操作className。抽离了classnames组件中的操作类。

classNames: function() {
    var hasOwn = {}.hasOwnProperty;
    var classes = [];
    for (var i = 0; i < arguments.length; i++) {
        var arg = arguments[i];
        if (!arg) continue;
        var argType = typeof arg;
        if (argType === 'string' || argType === 'number') {
            classes.push(arg);
        } else if (Array.isArray(arg) && arg.length) {
            var inner = classNames.apply(null, arg);
            if (inner) {
                classes.push(inner);
            }
        } else if (argType === 'object') {
            for (var key in arg) {
                if (hasOwn.call(arg, key) && arg[key]) {
                    classes.push(key);
                }
            }
        }
    }
    return classes.join(' ');
}

下面就可以愉快的进行动态操作className了。

<div className="aa"></div>
<div className={domUtils.classNames('aa', {'success': opt.type})}></div>
<div className={domUtils.classNames('bb', opt.ok&&'anim-'+opt.ok)}></div>
<div className={domUtils.classNames('cc', opt.icon)}></div>

组件支持自定义拖拽手柄 drag:'#xxx',是否拖动到浏览器外面 dragOut:true,还支持iframe弹窗类型 type:'iframe'

另外还支持设置 topmost:true,让当前窗口保持最前。

okay,以上就是react.js开发自定义桌面端弹框组件。希望对大家有所帮助哈!✍

最后附上两个vue自定义组件

vue自定义滚动条组件:https://blog.csdn.net/yanxinyun1990/article/details/110394287

vue自定义手机端弹框:https://blog.csdn.net/yanxinyun1990/article/details/108951470

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaoyan_2018

你的鼓励将是我持续作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值