【问题标题】:How to set the zIndex on the drawer component如何在抽屉组件上设置 zIndex
【发布时间】:2020-12-30 11:28:18
【问题描述】:

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

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

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

因此,我想将我的临时抽屉设置为 1250 的 z-index 并将我的 appbar 的 z-index 设置为 1251 以获得所需的效果而没有任何副作用。

我正在尝试使用makeStyles 挂钩设置 zIndex,正如您在沙箱中看到的那样,还有下面的 sn-p:

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>

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

【问题讨论】:

    标签: javascript reactjs material-ui z-index


    【解决方案1】:

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

    const theme = createMuiTheme({
      zIndex: {
        appBar: 1251,
        modal: 1250,
      }
    });
    
    ...
    
    <ThemeProvider theme={theme}>
      <Demo />
    </ThemeProvider>,
    

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

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

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

    现场演示

    【讨论】:

    • 是的,谢谢,这似乎解决了问题。奇怪的是,现在我的组件有 classNameclassesstyle 道具。
    【解决方案2】:

    您的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"
      },
      ...
    }));
    

    【讨论】:

    • 感谢您的回复。我知道如果你真的想在 css 中设置一些样式,你可以使用!important 语法。但我不是使用它的忠实粉丝。还有其他方法吗?
    • 目标是覆盖该内联样式;您可以创建一个外部 css 文件并使用更具体的选择器。
    猜你喜欢
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多