[英]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.