简体   繁体   English

如何使用 React 创建覆盖?

[英]How to create an overlay with React?

I'm trying to make an overlay that will appear when I clicked the menu button and close when clicked anywhere on the page.我正在尝试制作一个覆盖,当我单击菜单按钮时会出现该覆盖,并在单击页面上的任何位置时关闭。 But nothing is happening when I clicked the button.但是当我点击按钮时什么都没有发生。

I'm still new to React Hooks, so I hope you'll understand if I make obvious mistakes.我还是 React Hooks 的新手,所以如果我犯了明显的错误,希望你能理解。

Here are my codes:这是我的代码:

App.js应用程序.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应用程序.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;
}

Here's a link to CodeSandbox这是CodeSandbox的链接

In your styles.css , you are setting the CSS display property to none .在您的styles.css中,您将 CSS display属性设置为none This should be changed to display: block .这应该更改为display: block

The Modal will then be only displayed when the value of open is true .只有当open的值为true时,才会显示 Modal。

you probably found the answer already but you'll need to change your display: none to display: block and then use visibility: hidden (when the modal is closed) and visibility: visible when the modal is open您可能已经找到了答案,但您需要更改您的 display: none to display: block 然后使用 visibility: hidden (当模态关闭时)和 visibility: visible 当模态打开时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM