具有独立滚动列的材质 UI 网格

IT技术 html css reactjs material-ui
2021-05-05 14:32:18

我希望在 React 中使用 Material UI 制作多个滚动列。我有一种在引导程序中使用 flex 进行的方法,但我无法将其翻译过来。我已经整理了一个 hacky 方法的演示,它需要知道你想要滚动的内容的大小(在这种情况下,AppBar)

https://codesandbox.io/s/pmly895mm

html,
body {
  margin: 0;
  height: 100%;
}

#root {
  height: 100%;
}

.grid-container {
  height: calc(100% - 64px);
}

.grid-column {
  height: 100%;
  overflow-y: auto;
}

在这个演示中,我将所有高度设置为 100%(html、body、#root),然后创建了两个grid-container高度为 100% 的类 - AppBar 高度和grid-column高度为 100% 并且溢出-y 为 auto。

在 Bootstrap 中,我会将这些类分别应用于rowcolumn元素

.flex-section {
  flex-grow: 1;

  display: flex;
  flex-direction: column;

  min-height: 0;
}

.flex-col-scroll {
  flex-grow: 1;

  overflow: auto;

  min-height: 100%;
}

元素上方的内容并不重要,因为 flex 负责处理高度。

具体来说,我希望避免这样做,height: calc(100% - 64px)因为这需要我事先知道元素高度。我将有一些页面,我想在滚动区域上方放置一些内容,这些内容将具有动态的高内容。

4个回答

在我决心重新创建我过去在引导程序 ( https://jsfiddle.net/aq9Laaew/226591/ ) 中的做法时,我实际上也能够让它在 Material UI 中工作。由于我无法在此特定用例(React/Material UI 可滚动列)中找到任何在线示例,希望这对其他人有所帮助。

这是示例:https : //codesandbox.io/s/z24wl3n58m

html,
body {
  margin: 0;
  height: 100%;
}

#root {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.flex-section {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.flex-col-scroll {
  flex-grow: 1;
  overflow: auto;
  min-height: 100%;
}

.flex-no-shrink {
  flex-shrink: 0;
}

我缺少的是在根上设置 flex。一旦我们这样做了,那么我们就可以利用flex-section, flex-col-scroll, 和flex-no-shrink(后者用于防止滚动上方的元素被压缩)

2020 更新

FWIW 我只能将这两个样式属性添加到Box组件中以实现可滚动<div>列:

<Box style={{maxHeight: '100vh', overflow: 'auto'}}>...</Box>

你只需要修复你的导航栏。它将保持完好无损。之后,向您添加一个填充,grid container它将包含您的所有内容。您甚至可以提供百分比填充以确保响应性。

这是工作代码和框:固定导航栏

如果问题仍然存在,请告诉我。

我发现使用 Material UI 的 Grids 真的很难做到这一点,因为正如在对另一个答案的评论中指出的那样,如果没有“flex-wrap: nowrap”和添加“flex- wrap: nowrap" 破坏了 Material UI 的网格布局系统。

然而,我确实发现,如果我使用 Material UI 的 Boxes 而不是 Grids ,我可以很容易地重现 Josh Sherman 的具有固定标题和独立滚动列布局

在 index.html 中:

<style>
  body,
  html,
  #root {
    height: 100%;
  }
</style>

#root 当然是由 create-react-app 创建的。

在 App.tsx 中:

import React from "react";
import { AppBar, Box, Toolbar } from "@material-ui/core";

function App() {
  return (
    <>
      <AppBar>
        <Toolbar />
      </AppBar>
      <Box flexDirection="column" display="flex" height="100%">
        <Toolbar />
        <Box flexGrow={1} display="flex" overflow="hidden">
          <Box overflow="auto">
             <!-- The contents of the left column go here -->
          </Box>
          <Box overflow="auto">
            <!-- The contents of the right column go here -->
          </Box>
        </Box>
      </Box>
    </>
  );
}

export default App;