繁体   English   中英

具有动态高度的 React Material-Ui 粘性表头

[英]React Material-Ui Sticky Table Header with Dynamic Height

我正在使用 React 的 Material-UI 框架来显示表格。 我想使用粘性标题; 但是,我不想在我的桌子上设置高度,因为我希望它随着页面滚动。 除非我在 TableContainer 上设置高度,否则以下代码段不会粘贴标题。

https://codesandbox.io/s/winter-firefly-5wlx2?file=/src/App.js

import React from "react";
import {
  TableContainer,
  Table,
  TableHead,
  TableRow,
  TableCell
} from "@material-ui/core";
import "./styles.css";

export default function App() {
  return (
    <TableContainer>
      <Table stickyHeader>
        <TableHead>
          <TableRow>
            <TableCell>Value</TableCell>
          </TableRow>
        </TableHead>
        {
          Array(100).fill("Test").map((e) => <TableRow><TableCell>{e}</TableCell></TableRow>)
        }
      </Table>
    </TableContainer>
  );
}

摆脱TableContainer overflow-x: auto它应该可以工作

const useStyles = makeStyles({
  customTableContainer: {
    overflowX: "initial"
  }
})

export default function App() {
  const classes = useStyles();
  return (
    <TableContainer classes={{root: classes.customTableContainer}}>
      <Table stickyHeader>
      
      ...

编辑cool-shadow-59lrh

参考: https : //css-tricks.com/dealing-with-overflow-and-position-sticky/

实际上我面临着类似的事情,我希望我的桌子是可用高度的 100%,所以我给父标签而不是桌子提供了 100% 的高度,然后在我的桌子中用我的桌子制作了父母高度的计算容器参考,实现将是这样的

 // 1. create a ref const tableContainerRef = useRef(null); // 2. wait until the container ref is populated and retrieve the parents height const containerMaxHeight = useMemo(() => { if (!tableFormRef.current) return null; return tableFormRef.current.parentElement.clientHeight; }, [tableFormRef.current]); // 3. use the height of the parent as your table's maxHeight return ( <div ref={tableContainerRef}> <TableContainer style={{maxHeight: containerMaxHeight}}> <Table> ... </Table> </TableContainer> </div> );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM