如何在抽屉组件上设置 zIndex

How to set the zIndex on the drawer component

我正在尝试实现 clipped under the app bar 风格的临时抽屉。但是我似乎无法在临时抽屉上设置z索引。

material-ui 中的临时抽屉具有 modal 组件的 z-index,即我在此处提出的问题中提到的 1300 https://github.com/mui-org/material-ui/issues/22562.

因此,如果我使用文档中提供的将应用栏 zIndex 设置为 theme.zIndex.modal + 1 的方法,我可以获得“在应用栏下剪辑”的效果。但这也意味着我的应用栏将高于我的所有模式。这不是我想要的。

所以,我想将我的临时抽屉设置为 1250 的 z-index,并将我的应用栏的 z-index 设置为 1251,以获得没有任何副作用的预期效果。

我正在尝试使用 makeStyles 挂钩设置 zIndex,正如您在沙盒中看到的以及下面的代码片段:

const useStyles = makeStyles((theme) => ({
  appBar: {
    zIndex: 1251
  },
  drawer: {
    width: drawerWidth,
    flexShrink: 0,
    zIndex: 1250
  },
  drawerPaper: {
    width: drawerWidth
  }
}));
<AppBar position="fixed" className={classes.appBar}>
   .
   .
   .
</AppBar>
      
<Drawer
  className={classes.drawer}
  open={true}
  classes={{
    paper: classes.drawerPaper
  }}
>
   .
   .
   .
</Drawer>

codesandbox: https://codesandbox.io/s/material-demo-forked-rq1fj?file=/demo.js

您的 z-index: 1250 被 material-ui 添加的内联 z-index: 1300 覆盖。您可以通过将 !important 添加到您的自定义 z-index.

来覆盖此内联样式
const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex"
  },
  appBar: {
    zIndex: 1251
  },
  drawer: {
    width: drawerWidth,
    flexShrink: 0,
    zIndex: "1250 !important"
  },
  ...
}));

如果您不想使用 important!,您可以通过使用 Material-UI 主题 API 或内联样式来覆盖 zIndex

const theme = createMuiTheme({
  zIndex: {
    appBar: 1251,
    modal: 1250,
  }
});

...

<ThemeProvider theme={theme}>
  <Demo />
</ThemeProvider>,

这种方法的缺点是样式应用于所有模态,因此您的实际模态现在低于 AppBar,这可能不是您想要的。

第二种方法是通过在组件的样式属性中传递样式对象来内联 css 样式

<AppBar
  className={classes.appBar}
  style={{ zIndex: 1251 }}
>
</AppBar>
<Drawer
  className={classes.drawer}
  style={{ zIndex: 1250 }}
>

现场演示