此方法使用 React Portal。你的索引 html 文件中应该有 id="modal-root" 的元素。每次调用modal时,modal都会进入modal-root里面,因此不会有z-index的问题,因为你将Modal渲染在最顶层的div
创建一个文件 Modal.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
const modalRoot = document.getElementById('modal-root');
class Modal extends Component {
constructor(props) {
super(props);
this.el = document.createElement('div');
}
componentDidMount() {
modalRoot.appendChild(this.el);
console.log('Modal did mount');
}
componentWillUnmount() {
console.log('Modal will unmount');
modalRoot.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(
this.props.children,
this.el,
);
}
}
export default Modal;
创建实际的模态代码
import React from 'react';
const ImageContainer = props => (
<div className="modal d-block full-screen-popup" tabIndex="-1" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h6 className="modal-title text-center bold">Title</h6>
<button type="button" className="close" onClick={props.onClose}>
<span className="icon-close" />
</button>
</div>
<div className="modal-body p-0">
<div className="imageBody text-center">
<img className="img-fluid" src={props.imgSrc} />
</div>
</div>
</div>
</div>
</div>
);
export default ImageContainer;
它的 CSS 应该是
.full-screen-popup {
background-color: rgba(0,0,0,.62);
}
.d-block {
display: block!important;
}
.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
display: none;
outline: 0;
}
然后在任意一个 js 文件中,导入 Modal,并传递实际的 modal 组件。
renderImageModal = () => {
if (this.state.showImageModal) {
return (
<Modal>
<ImageContainer onClose={this.handleImageModalClose} imgSrc={this.state.link} />
</Modal>);
}
return null;
}
handleModalOpenClick = () => {
this.setState({
showImageModal: true,
});
}
handleImageModalClose = () => {
this.setState({
showImageModal: false,
});
}
render(){
return(
<button onclick={this.handleModalOpenClick}>Open Modal</button>
{this.renderImageModal()})
}