【问题标题】:How to create an overlay with React?如何使用 React 创建覆盖?
【发布时间】: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


    【解决方案1】:

    在您的 styles.css 中,您将 CSS display 属性设置为 none。这应该改为display: block

    只有当open 的值为true 时才会显示模态框。

    【讨论】:

    • 好的,更改为display: block 将使覆盖生效。但这又产生了另一个问题。覆盖层已经打开,它应该从一开始就隐藏起来,直到我点击按钮。
    【解决方案2】:

    您可能已经找到了答案,但您需要更改您的 display: none 以 display: block 然后使用 visibility: hidden (当模态关闭时)和 visibility: visible 当模态打开时

    【讨论】:

      猜你喜欢
      • 2018-10-21
      • 2016-07-22
      • 2011-12-27
      • 1970-01-01
      • 2014-08-05
      • 2014-11-15
      • 2023-04-05
      • 2012-01-02
      • 1970-01-01
      相关资源
      最近更新 更多