我已经在模态上使用html和css在react中创建了,但是当我将模态的z索引设置为更高
时,模态在环境中部署时无法正常工作。但是,页面上还有其他组件也具有z索引,并且这些组件出现在html页面订单中的模态组件之前。
型号不会出现在预期的上方。
有任何反应的方式,因此我们可以覆盖所有现有的z索引,而模态将按预期工作。我正在为模态覆盖和模态提供CSS代码
.modal-overlay{
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
z-index: 5;
background-color: rgba(0,0,0,0.3);
overflow: scroll;
}
.modal{
display: flex;
flex-direction: column;
flex-basis: auto;
background-color: #fff;
max-width: 375px;
margin: 0px auto;
}
此方法使用React Portal。u应该在UR索引HTML文件中具有ID ="模态root"的元素。每次您调用模态时,模态都会进入模态 - 因此,z索引没有问题,因为在最上方呈现模态时
创建一个文件模态
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文件中,导入模态,然后传递实际模态组件。
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()})
}
使用ReactJS
创建模态的最佳方法是使用Portals
。
您可以在ReactJS文档中查看文档是否有门户网站或此处的特定Modal
codepen上的示例。