【问题标题】:Is there a way to move children to another parent if they overflow the current parents height?如果孩子超出当前父母的身高,有没有办法将孩子转移到另一个父母那里?
【发布时间】:2023-01-07 21:10:55
【问题描述】:
我使用 React 编写 Web 应用程序。我有一个 Container 组件,用作具有固定高度的容器。在这个Container我有多个身高不一的孩子。有没有办法以编程方式复制 Container 组件并将其溢出第一个容器高度的子组件移动到复制的容器中。并且,如果可能,递归地执行此操作(这样我们就可以拥有多个复制的容器)。
我能想到的唯一例子是当你想在文档的新页面上打印或写东西时的分页符,但在这种情况下,我想在网页上执行此操作而不进行任何打印。
这是我目前拥有的代码:
容器:
const Container = ({ children }) => {
return <div style={{ height: "500px" }}>{children}</div>;
}
页:
return (
<Container>
<div style={{ height: 250, width: "100%", border: "2px solid black" }}></div>
<div style={{ height: 250, width: "100%", border: "2px solid black" }}>
{/* Elements below should be moved to a new container */}
<div style={{ height: 200, width: "100%", border: "2px solid black" }}></div>
</div>
<div style={{ height: 200, width: "100%", border: "2px solid black" }}></div>
</Container>
)```
【问题讨论】:
标签:
javascript
css
reactjs
jsx
【解决方案1】:
我遇到过和你类似的问题,我就是这样解决的。
我已将它添加到您的代码中,希望它能正常工作。
import React, { useRef, useEffect } from "react";
const Container = ({ children }) => {
const containerRef = useRef(null);
const overflowRef = useRef(null);
useEffect(() => {
const container = containerRef.current;
const overflow = overflowRef.current;
if (container && overflow) {
if (container.offsetHeight < overflow.offsetHeight) {
// Move the overflowing elements to a new container
const newContainer = document.createElement("div");
newContainer.style.height = `${overflow.offsetHeight - container.offsetHeight}px`;
newContainer.style.border = "2px solid black";
while (overflow.firstChild) {
newContainer.appendChild(overflow.firstChild);
}
container.appendChild(newContainer);
}
}
}, [children]);
return (
<div style={{ height: "500px", position: "relative" }} ref={containerRef}>
<div style={{ height: "100%", width: "100%", position: "absolute" }} ref={overflowRef}>
{children}
</div>
</div>
);
};
const Page = () => {
return (
<Container>
<div style={{ height: 250, width: "100%", border: "2px solid black" }}></div>
<div style={{ height: 250, width: "100%", border: "2px solid black" }}>
{/* Elements below should be moved to a new container */}
<div style={{ height: 200, width: "100%", border: "2px solid black" }}></div>
</div>
<