reactjs - 使当您单击块内的项目时,会出现另一个块(每个块都有自己的)
问题描述
有一个有 3 个 div 的主单元。您需要单击每个 div 以打开其内容,并关闭主块和内部块。换句话说,只有打开的块才能通过单击保留在页面上。我不知道如何实现这一点。尤其是打开这个 div 的内容,而不是一个所有的。
我试图在图片中解释这一切。
解决方案
是你要找的吗?在 Stackblitz 上重现
如果您无法访问 stackblitz,以下是代码:
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
const App = () => {
// Hide/show main blocks
const commonAction = () => {
document.getElementById("container").classList.toggle("flex-col");
Array.from(document.getElementsByClassName("block")).forEach(el => {
el.classList.toggle("hidden");
});
};
// On click on the main block
const enlarge = e => {
commonAction();
// Just show the one we clicked
e.target.classList.remove("hidden");
// Enlarge it
e.target.classList.add("enlarge");
// show/hide its details
e.target.childNodes[1].classList.toggle("hidden");
};
// On click on the details
const hide = e => {
// Hide it
e.target.classList.add("hidden");
// reset main blocks to their original state
commonAction();
//reset main clicked block to its normal state
const parent = e.target.closest(".block");
parent.classList.remove("hidden");
parent.classList.remove("enlarge");
e.stopPropagation();
};
return (
<>
<div id="container">
<div className="block" onClick={enlarge}>
Content 1
<div className="block-content hidden" onClick={hide}>
Content details 1
</div>
</div>
<div className="block" onClick={enlarge}>
Content 2
<div className="block-content hidden" onClick={hide}>
Content details 2
</div>
</div>
<div className="block" onClick={enlarge}>
Content 3
<div className="block-content hidden" onClick={hide}>
Content details 1
</div>
</div>
</div>
</>
);
};
render(<App />, document.getElementById("root"));
CSS:
#container {
display: flex;
justify-content: space-between;
height: 200px;
}
.flex-col{
flex-direction: column;
}
#container > * {
position: relative;
min-width: 25%;
background-color: #6dd4fd;
}
.block-content {
position: absolute;
background-color: #ffb35c;
top:0;
bottom:0;
left:0;
right:0;
}
.hidden{
visibility: hidden;
height:0px !important;
}
.enlarge{
width: 100% !important;
height: 100% !important;
display: block;
}