一、react-modal
官方定义: Accessible modal dialog component for React.JS理解: 一个容易使用的React模态框组件
二、用法
有时候我们不用一些UI框架的时候(bs3.0、antd),就需要自己封装一些模态框.自己定义各种回调事件...等等这时候可以考虑用一个npm模态框的包
安装
``` $ npm install react-modalimport ReactModal from 'react-modal'
<h4>事件</h4>
<b>isOpen</b>: 模态框状态控制
<b>onAfterOpen</b>: 模态框打开后的回调事件
<b>onRequestClose</b>: 模态框关闭后的回调事件
<b>style</b>: 模态框样式,默认以`content`为默认应用名
<b>contentLabel</b>: 内容label
<h3>和React结合</h3>
import React,{ PureComponent } from 'react'
import ReactModal from 'react-modal'
const customStyles = {
content: {
'300px',
height: '300px',
top: '50%',
left: '50%',
transform: 'translate(-50%, -55%)'
},
btn: {
marginTop: 30,
background: 'transparent',
padding: '10px 15px'
}
};
ReactModal.setAppElement('#root')
export default class ReactModalComp extends PureComponent{
constructor(arg){
super(arg)
this.state = {
modalOpenState: false,
}
this.openModal = this.openModal.bind(this)
this.closeModal = this.closeModal.bind(this)
}
openModal(){
this.setState({
modalOpenState: true,
})
}
closeModal(){
this.setState({
modalOpenState: false,
})
}
afterOpenModalEv(){
console.log('==========> 打开')
}
render(){
const { modalOpenState } = this.state;
return(
<div className="reactModal">
<button onClick={this.openModal} style={customStyles.btn}>打开</button>
<ReactModal
isOpen = {modalOpenState}
style={customStyles}
contentLabel="Example Modal"
onAfterOpen={this.afterOpenModalEv}
>
<form>
<input />
<p>tab navigation</p>
<p>stays</p>
<p>inside</p>
<p>the modal</p>
</form>
<button onClick={this.closeModal}>关闭</button>
</ReactModal>
</div>
)
}
}
![](https://img2018.cnblogs.com/blog/1414709/201810/1414709-20181003132007954-341535996.png)
<h4>更多DEMO</h4>
<a href="https://codepen.io/claydiffrient/pen/KNxgav" target="_blank">《基础Modal》</a>
<a href="https://codepen.io/claydiffrient/pen/KNjVBx?editors=1111" target="_blank">《结合onRequestClose》</a>
<a href="https://codepen.io/claydiffrient/pen/KNjVrG" target="_blank">《使用样式的Modal》</a>
<a href="https://codepen.io/claydiffrient/pen/woLzwo" target="_blank">《shouldCloseOnOverlayClick》</a>