【问题标题】:How can I make my layout adapt to the Material-UI toolbar height?如何让我的布局适应 Material-UI 工具栏的高度?
【发布时间】:2021-04-30 08:59:56
【问题描述】:

我目前正在构建布局组件(导航栏、页脚和内容),它看起来像这样:

// containers/Layout/index.jsx
export default function Layout({ children }) {
  const classes = useStyles();

  return (
    <>
      <Navbar />
      <main className={classes.root}>{children}</main>
      <Footer />
    </>
  );
}

这些是样式:

// containers/Layout/styles.js
export default makeStyles((theme) => ({
  root: {
    minHeight: `calc(100vh - 64px - ${theme.mixins.toolbar.minHeight}px)`,
  },
}));

现在我遇到了一个问题,Material-UI Toolbar 是响应式的。我的页脚是64px 高,但我的应用栏当然是动态的。

// component/Appbar/index.jsx
export default function Navbar() {
  return (
    <AppBar position="static">
      <Toolbar />
    </AppBar>
  );
}

作为参考,这是 mixin 的样子:

我正在尝试获取AppBar 的当前高度,以便我可以使我的calc 函数响应。我试过使用 mixin,但它只返回正常的最小高度。另一种选择是使用媒体查询,但我不想这样做,因为媒体查询已经存在于工具栏混合中。

如何获得这个最小高度以正确适应屏幕尺寸?我的目标是始终用底部的页脚填充 100% 的屏幕,并用内容填充剩余空间。

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    你可以看到工具栏here的默认mixins:

    toolbar: {
      minHeight: 56,
      [`${breakpoints.up('xs')} and (orientation: landscape)`]: {
        minHeight: 48,
      },
      [breakpoints.up('sm')]: {
        minHeight: 64,
    },
    

    它将minHeight 设置为不同屏幕尺寸/方向的不同值。同样,在标题下方的主要内容中,您应该将height 设置为如下内容:

    content: {
      height: `calc(100vh - 56px)`,
      [`${theme.breakpoints.up("xs")} and (orientation: landscape)`]: {
        height: `calc(100vh - 48px)`
      },
      [theme.breakpoints.up("sm")]: {
        height: `calc(100vh - 64px)`
      }
    }
    

    现场演示

    【讨论】:

    • 谢谢!所以没有像calc(64px - ${some_calculated_height})这样的选项来将它们全部放在一行中?
    • @Thimma by some_calculated_height,你的意思是你想找到一种更简洁的编码方式,还是你想使用静态值some_calculated_height?如果是前者,那么答案是否定的。否则,您始终可以使用 createMuiTheme 中的值覆盖工具栏 mixins。
    • 对于计算出的高度,我的意思是像一个变量,它会根据使用 mixin 的屏幕尺寸而变化,所以我不必做 3 个相同查询的副本,如果那是不可能的,那就太酷了太
    • @Thimma 缓解这种情况的一种方法是在我的代码和框中放置一个指向默认 mixins 值的链接,以便未来的维护者可以理解为什么会有重复的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 2016-10-14
    • 1970-01-01
    • 2016-02-01
    相关资源
    最近更新 更多