如何将Material-UI的Drawer组件定位在AppBar组件下方
解决方案
可以实现该需求,你当前添加padding不生效的核心原因是:Material-UI的Drawer组件的可见内容是由内部Paper子元素渲染的,默认采用固定定位,你给Drawer外层容器添加的样式不会作用到内部的内容容器上。
1. 调整样式定义
修改makeStyles中的样式,新增专门控制Drawer内部Paper的样式规则:
const useStyles = makeStyles((theme) => ({ root: { display: 'flex', }, appBar: { zIndex: theme.zIndex.drawer + 1, }, title: { flexGrow: 1, }, toolbar: { display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), ...theme.mixins.toolbar, }, content: { flexGrow: 1, padding: theme.spacing(3), }, // 新增控制Drawer内部内容容器的样式 drawerPaper: { // 顶部间距等于Toolbar高度,自动适配响应式 marginTop: theme.mixins.toolbar.minHeight, // 抽屉高度占剩余视口高度,避免超出屏幕 height: `calc(100vh - ${theme.mixins.toolbar.minHeight}px)` }, }));
2. 调整组件传参
将新增的样式通过classes属性传入Drawer组件,指定覆盖内部paper元素的样式:
<div className={classes.root}> <AppBar position="absolute" > <Toolbar> <Typography component="h1" variant="h6" noWrap className={classes.title}> x </Typography> <Switch checked={isDarkTheme} onChange={handleThemeSwitch}/> <WbIncandescentIcon /> </Toolbar> </AppBar> <ServiceDrawer classes={{ paper: classes.drawerPaper }} onOperationSelected={onOperationSelect} serviceList={services} onDrawerOpen={onDrawerOpen} onDrawerClose={onDrawerClose}> </ServiceDrawer> <main className={classes.content}> <div className={classes.toolbar} /> {selectedOperation && <Operation operation={selectedOperation}/>} </main> </div>
注意事项
- 如果你封装的
ServiceDrawer组件没有透传classes属性,需要在ServiceDrawer内部将该属性传递给它引用的原生MUI Drawer组件。 - 使用
theme.mixins.toolbar.minHeight获取Toolbar高度可以自动适配不同响应式断点下的AppBar高度,无需手动写死数值,适配性更好。 - 若你使用的是临时抽屉(
variant="temporary"),该方案同样生效,无需额外调整。
内容的提问来源于stack exchange,提问作者Dominique M
相关产品推荐
相关产品推荐

