React开发一个通过方法调用的弹框组件
- 常见的函数调用的组件有toast,loading等,今天来详细介绍下方法调用的弹框组件,该组件为自定义内容组件,需要展示什么可自行写入,这里仅展示思路和单一的业务ui。
- 调用时支持的全部传参:title, content,okbtn,marginTop,hasBottom,styles,showX,timeout
- title:标题
- content: 内容,
- okbtn:确定/关闭按钮
- marginTop : 距离顶部的距离
- hasBottom:是否有底部内容
- styles: 弹框的样式
- showX: 是否展示关闭icon
- timeout:延迟多少时间自动关闭弹框
代码如下:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
// 这是一个自定义内容的弹框
class SigoModal extends Component {
constructor(props) {
super(props)
this.state = {}
}
componentDidMount(){
// 需要延迟自动关闭弹框时可传入
let timeout = this.props.timeout
if(timeout) {
setTimeout(() => {
this.onClose()
}, timeout);
}
}
onClose = () => {
// 执行关闭的回调
this.props.onClose()
// 移除模态框
const modal = document.getElementById('condiv1')
document.body.removeChild(modal);
}
render() {
let { title, content,okbtn,marginTop,hasBottom,styles,showX,timeout } = this.props;
return (
<div className='mask'>
{hasBottom?hasBottom():null}
<div className="modal" style={styles || {marginTop:marginTop?marginTop:'1.6rem'}}>
<div className='title'>
<div>{title()}</div>
</div>
<div className='content'>{content()}</div>
<div className='btn' onClick={this.onClose}>{okbtn()}</div>
{showX?<span onClick={this.onClose} class="icon iconfont icon-btn_scx icon_x"></span>:null}
<style>
{
`
.mask {
position: fixed;
top: 0;
right: 0;
left: 0;
bottom: 0;
background: rgba(0,0,0,.7);
height: 100%;
z-index: 1001;
}
.modal {
position: relative;
margin: 1.6rem auto 0;
width: 85%;
border-radius:.12rem;
background:#fff;
}
.title {
width:100%;
}
.btn {
cursor: pointer;
}
.icon_x {
position:absolute;
right: 10px;
top: 10px;
font-size: .64rem;
color: #D9D9DA;
}
`
}
</style>
</div>
</div>
)
}
}
// props类型检查
SigoModal.propTypes = {
title: PropTypes.func.isRequired,
content: PropTypes.func.isRequired,
okbtn: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
styles: PropTypes.object
}
export function sigomodal(obj) {
let ConDiv = document.createElement('div');
ConDiv.id = 'condiv1'
document.body.appendChild(ConDiv);
let props = {
title: obj.title,
content: obj.content,
okbtn:obj.okbtn,
onClose:obj.onClose,
marginTop: obj.marginTop,
hasBottom: obj.hasBottom,
styles:obj.styles,
showX:obj.showX,
timeout: obj.timeout
}
ReactDOM.render(<SigoModal {...props} />, ConDiv);
}
调用方式
sigomodal({
marginTop: '45%',
title:()=>{},
content:()=>{
return (
<div style={{textAlign:'center',padding:'24px 0'}}>
<img src='/static/images/promote_tips.png' style= {{width:'2.54rem',height:'1.86rem'}} />
<p style={{fontWeight:'700',fontSize:'.36rem',color:'#323232',margin:'.16rem 0 8px'}}>提现申请已提交</p>
<p style={{fontSize:'.24rem',color:'#828286'}}>提现审核中,请关注进度</p>
</div>
)
},
okbtn:()=>{},
onClose:()=>{},
showX: true,
timeout: 3000
})
效果如下