我已经在模态中使用HTMl和CSS创建了反应,但是模态在环境中部署时没有按预期工作,因为我已将模态的z-index设置为更高
但页面上还有其他组件也有z-index,并且这些组件在html页面顺序中出现在模态组件之前。
模型未按预期显示在顶部。
是否有任何反应方式,以便我们可以覆盖所有现有的z-index,并且模态将按预期工作。 我正在为模态叠加和模态提供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;
}
答案 0 :(得分:1)
此方法使用React Portal。你应该在你的索引html文件中有id =“modal-root”的元素。每当你调用一个模态时,模态将进入模态根,因此不存在z-index的问题,因为你在最顶层 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文件中,导入模态,并传递实际的模态组件。
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()})
}
答案 1 :(得分:-2)