gpt4 book ai didi

javascript - React/Redux/CSS - 模态放置

转载 作者:太空宇宙 更新时间:2023-11-04 01:07:53 25 4
gpt4 key购买 nike

我有一个 Card 和一个 Modal 组件,就像这样

class Card extends Component {
constructor() {
super();
this.state = { showModal: false }
}

render() {
const { showModal } = this.state;
return (
{/* Some code */}
{showModal && <Modal />}
)
}
}

因此,在需要时我不想呈现我的Modal。逻辑。

在这种情况下,Modal 的工作是显示Card 组件的全部内容(Card 有一个固定的高度,所以我无法在其中显示所有信息)。


现在,在更高的层次上,我有以下内容:

class App extends Component {
/* Some Code */
render() {
return (
<div>
<Content /> {/* Our content */}
<Overlay /> {/* Our all-purpose-overlay (we need it for the Modal) */}
</div>
)
}
}

问题是我的 Card 组件具有 position: relative 样式,而 Modal 组件具有 z-index 和样式 position: absolute

I did some research and I read that nested elements with non-static position will not work the same way regarding the z-index. The z-index will take effect only within the non-static element.

所以我不能让我的 Modal 出现在 Overlay 组件之上。此外,Card 组件有一个 overflow:hidden 属性。因此,Modal 被裁剪了。

这里是一个简单的演示。

function toggleModal() {
var app = document.getElementById("app");
app.classList.toggle("-modal");
}
:root {
background: #ddd;
}

#app,
#overlay {
height:100vh;
width:100%;
}

#app {
display: flex;
align-items: center;
justify-content: center;
}

/* Overlay */

#overlay {
position: absolute;
top: 0;
left: 0;
z-index: 1;

visibility: hidden;
background: rgba(0,0,0,0.3);
}

.-modal #overlay {
visibility: visible !important;
}

/* Card */

#card {
position: relative;
width: 250px;
padding: 1em;
border-radius: 5px;
background: white;
overflow: hidden; /* Problem */
}

.content {
padding: 4em 0;
text-align: center;
}

.btn {
padding: 1em 2em;
border:none;
color:white;
float: right;
cursor: pointer;
transition: 0.2s ease;
background: #00abff;
}

.btn:hover {
background: #0c9de4;
}

/* Modal */
#modal {
width: 300px;

position: absolute;
top:0;
left: 50px; /* Modal Gets clipped */

visibility: hidden;
background-color:red;
}

.-modal #modal {
visibility: visible;
}
<div id="app">
<div id="card">
<div class="content">content</div>
<button class="btn" onclick="toggleModal()">Display Modal</button>
<div id="modal">
<div class="content">
<div>Modal</div>
<div>With same content</div>
<div>(under the Overlay and also cropped)</div>
</div>
</div>
</div>
<div id="overlay" onclick="toggleModal()"></div>
</div>


问题:我应该如何组织我的组件,这样我就不会遇到这个问题?

我想在顶层只有一个 Modal。然后我简单地显示它。但我需要将 Cardchildren 渲染到 Modal 中。

我应该如何进行?

最佳答案

由于您使用的是 React,我实际上建议使用 Portal 来呈现您的模态。 Portals 在 React 中解决的一件事就是这个问题。如果您使用的是更新版本的 React (16+),那么 you already have access to portals .

如果您使用的是旧版本的 React,那没关系。 You can use an implementation like this (react-portal) instead .

现在,您将在包含 <div> 的上下文之外的完全独立的 React 树中呈现您的组件/标记。有 position: relative在其上,您可以将其绝对定位或固定定位到任何需要的位置。

关于javascript - React/Redux/CSS - 模态放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51792490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com