[英]How to overlay a React component over a scrollable div?
我一直試圖讓我的 React 組件覆蓋在 Div 之上,但過去幾個小時我一直沒有運氣。 我發現這個StackOverflow 示例正是我正在尋找的,但它不起作用。 我試圖刪除我的代碼中大部分不相關的部分,並且我正在使用樣式化組件:
const Container = styled.div`
position: relative;
margin-top: 24px;
width: 80%;
height: 60%;
overflow-y: auto;
`;
const Inner = styled.div`
position: relative;
height: 100%;
width: 100%;
`;
const Overlay= styled.div`
position: absolute;
z-index: 1;
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
`;
function FileSystem() {
return (
<Container>
<Inner>
<Overlay>I want this to not scroll</Overlay>
<FileList />
</Inner>
</Container>
);
}
當它呈現時,我希望它不滾動被覆蓋並在父容器中居中。 但是,一旦填充了 FileList 組件並導致 div 溢出,它就會停止工作,並且我希望它不會與 FileList 組件一起滾動。 我如何讓它保持在同一個位置而不是與父母一起滾動?
這與應用overflow-y: scroll;
有關。 到您想要具有滾動行為的 div 。
換一種說法:不是應用 CSS 來保持覆蓋層固定,而是應用overflow-y: scroll;
到另一個 div (在您的情況下,將是另一個包含 div 內容的樣式 div)。
就像是:
const Container = styled.div`
position: relative;
margin-top: 24px;
width: 80%;
height: 60%;
overflow-y: auto;
`;
const Inner = styled.div`
position: relative;
height: 100%;
width: 100%;
`;
const Overlay= styled.div`
position: absolute;
z-index: 1;
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
`;
//This is the new styled div to contain the area you want to scroll
const ScrollableDiv = styled.div`
overflow-y: scroll;
`;
function FileSystem() {
return (
<Container>
<Inner>
<Overlay>I want this to not scroll</Overlay>
//This is the new div to add
<ScrollableDiv>
<FileList />
</ScrollableDiv>
</Inner>
</Container>
);
}
注意:上面的代碼我沒有測試,所以是定向的。 我不確定position: absolute;
疊加層上會交互。
下面問題的答案使我開始工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.