【发布时间】:2020-05-12 10:39:15
【问题描述】:
我正在尝试制作一个叠加层,当我单击菜单按钮时会显示该叠加层,并在单击页面上的任何位置时关闭该叠加层。但是当我点击按钮时什么都没有发生。
我还是 React Hooks 的新手,所以如果我犯了明显的错误,希望你能理解。
这是我的代码:
App.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>
);
}
App.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的链接
【问题讨论】:
标签: javascript css reactjs react-hooks