我正在React中渲染模态。
我的index.html
如下:
<div id="root"></div>
<div id="modal"></div>
并且我所有的模态(通过门户)呈现为.modal
的子代。
每个模态元素具有以下形式:
<div class="modal-background open">
<!-- children -->
</div>
该类可以为modal-background open
或modal-background closed
。整个组件是:
interface OwnProps {
children: React.ReactNode
isOpen: boolean
onExit: () => void
}
export class Modal extends React.Component<OwnProps, any> {
_exit = () => this.props.onExit();
_renderModal = () => (
<div className={`modal-background ${this.props.isOpen ? "open" : "closed"}`} onClick={this._exit}>
{this.props.children}
</div>
);
render() {
if (this.props.isOpen) {
document.body.className += " no-scroll";
} else {
document.body.classList.remove("no-scroll");
}
let elem = document.querySelector("#modal");
if (elem == null) {
console.log("Could not render modal.");
return null;
}
return ReactDOM.createPortal(this._renderModal(), elem);
}
}
CSS如下:
.modal-background {
/* Other styling - this a dark backdrop for a modal child */
background-color: rgba(0,0,0,0.2);
transition: opacity 150ms ease-out;
&.closed {
opacity: 0;
pointer-events: none;
}
&.open {
pointer-events: all;
opacity: 1;
&:hover {
cursor: pointer;
}
}
}
所以我的模态的用法类似于<Modal><CustomModalElement/></Modal>
。
当我加载页面时,我的模式元素会短暂闪烁,表明它们在加载时并未隐藏(但稍后会瞬间显示)。
我可以通过在CSS中添加display: none
和display: inherit
来解决此问题,但是我错过了不错的过渡。
有更好的方法吗?
答案 0 :(得分:0)
不确定index.html
文件中是否需要执行其他操作,除了
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<div id="modal"></div>
对于您的Modal.js
,您可以尝试以下方法:
import React from "react";
import ReactDOM from "react-dom";
const Modal = props => {
return ReactDOM.createPortal(
<div className="ui dimmer modals visible active">
<div className="ui standard modal visible active">
<div className="header">Delete Object</div>
<div className="content">
Are you sure you want to delete this?
</div>
<div className="actions">
<button className="ui primary button">Delete</button>
<button className="ui button">Cancel</button>
</div>
</div>
</div>,
document.querySelector("#modal")
);
};
export default Modal;
,然后在您将要执行模态的其他组件内部:
import React from "react";
import Modal from "../Modal"; // or wherever your Modal is in the file tree
const ObjectDelete = () => {
return (
<div>
ObjectDelete
<Modal />
</div>
);
};
export default ObjectDelete;
请记住,我在此处提供的模式示例不是可重用的组件。