避免在弹出窗口上滚动条-位置:固定



当我点击一个按钮时,我有一个打开的边栏,我将它的位置设置为fixed,这样它就可以像这样占据整个屏幕(我使用TailwindCSS):

return (
<div className="fixed z-40 flex left-0 top-0 h-screen w-screen">
// this div set a gray color to the entire screen
<div className="w-full bg-zinc-500 fade-in"></div>
// this div is 600px wide on right of screen
<div className="bg-stone-100 w-600 bg-white">
<div className="p-8">
[ MY FORM ]
</div>
</div>
</div>
)

我将其设置为fixed,因为它是一个下组件,我需要它来克服标题和另一个在应用程序顶部调用的侧边栏。

下面是我的应用程序的结构:

function App() {
const AppLayout = () => (
<>
<Header />
<div className="flex">
<Sidebar />
<Outlet />
// the sidebar I'm trying to fix is in Outlet
</div>
</>
);

问题是:当我打开我的侧边栏(下图)时,它占据了整个屏幕,但是滚动条滚动的是这个侧边栏下的页面,而不是侧边栏中的内容。

知道如何禁用页面的滚动条,并为固定组件启用一个吗?

PS:这是一个重现问题的沙盒(正如你所看到的,我可以滚动页面,但不能弹出)

正如@iamhuynq在评论中提到的,设置overflow-auto和useEffect可以解决这个问题。谢谢!

当你打开侧边栏时,你可以通过设置溢出隐藏为主体来禁用页面滚动,当你关闭时删除。在侧边栏

上添加自动溢出
useEffect(() => {
const openSideBar = () => {
document.body.style.overflow = 'hidden';
};
const closeSideBar = () => {
document.body.style.overflow = '';
};
if (isOpenSidebar) openSideBar()
else closeSideBar()
return () => closeSideBar();
}, [isOpenSidebar]);

最新更新