[英]How to create an overlay with React?
我正在尝试制作一个覆盖,当我单击菜单按钮时会出现该覆盖,并在单击页面上的任何位置时关闭。 但是当我点击按钮时什么都没有发生。
我还是 React Hooks 的新手,所以如果我犯了明显的错误,希望你能理解。
这是我的代码:
应用程序.js
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const modalRoot = document.getElementById("modal-root");
const Modal = props => {
return ReactDOM.createPortal(
<div className="overlay">{props.children}</div>,
modalRoot
);
};
export default function App() {
const [open, setOpen] = React.useState(false);
return (
<div className="App">
<button onClick={() => setOpen(!open)}>Menu</button>
{open && <Modal in={open}>Click anywhere to close</Modal>}
</div>
);
}
应用程序.css
body {
font-family: sans-serif;
}
.App {
position: relative;
text-align: center;
}
* {
box-sizing: border-box;
}
.overlay {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
cursor: pointer;
}
这是CodeSandbox的链接
在您的styles.css
中,您将 CSS display
属性设置为none
。 这应该更改为display: block
。
只有当open
的值为true
时,才会显示 Modal。
您可能已经找到了答案,但您需要更改您的 display: none to display: block 然后使用 visibility: hidden (当模态关闭时)和 visibility: visible 当模态打开时
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.