【问题标题】:React Material-Ui Sticky Table Header with Dynamic Height具有动态高度的 React Material-Ui 粘性表格标题
【发布时间】:2021-01-17 17:26:28
【问题描述】:

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

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>
  );
}

【问题讨论】:

    标签: javascript css reactjs material-ui


    【解决方案1】:

    摆脱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>
          
          ...
    

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

    【讨论】:

    • 有什么方法可以在保持 100% 宽度的同时做到这一点?
    • 我没有触及 TableContainerwidth 属性 - 它仍然位于 100% width。如果您在我的代码中注释掉overflowX: "initial" - 您会看到它仍然与您的沙箱非常相似,我所做的唯一区别是在粘性标题上
    • 让我换个说法:有什么办法可以让 x 方向在表格内滚动,同时让 y 方向可以随页面滚动 - 同时保持粘性标题正常工作。
    • 很有可能。看看thisthis
    • 非常感谢,我已经寻找这个修复程序 2 天了
    【解决方案2】:

    实际上我遇到了类似的事情,我希望我的表格是可用高度的 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>
    );

    【讨论】:

      猜你喜欢
      • 2022-12-06
      • 1970-01-01
      • 2021-06-06
      • 2021-03-27
      • 1970-01-01
      • 2016-04-02
      • 2017-10-03
      • 1970-01-01
      • 2021-04-27
      相关资源
      最近更新 更多