【问题标题】:How to make react table to scrollable?如何使反应表可滚动?
【发布时间】:2021-11-09 11:26:36
【问题描述】:

我正在尝试使反应表可以水平和垂直滚动,但现在它正在根据数据占用所有空间。 我想让这个表格高度固定,并且可以双向滚动。

表格组件:

import React from "react";
import { useTable } from "react-table";

const Table = ({ columns, data }) => {
  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
    useTable({
      columns,
      data,
    });
  return (
    <table {...getTableProps()} className="text-center">
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th
                className="bg-primary-dark text-white p-4 text-center"
                {...column.getHeaderProps()}
              >
                {column.render("Header")}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody
        {...getTableBodyProps()}
        className="bg-primary-light text-primary-dark overflow-scroll"
      >
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

export default Table;

表格容器

import React, { useMemo } from "react";
import useData from "../../hooks/useData";
import Table from "./Table";

const TableSection = React.memo(({ query }) => {
  const { data, runtime, error } = useData(query);
  const column =
    data.length > 0 &&
    Object.keys(data[0]).map((key) => {
      return {
        Header: data[0][key],
        accessor: key,
      };
    });
  const columns = useMemo(() => column, [column]);
  const queryData = useMemo(() => data.slice(1), [data]);
  
  return (
    <div className="col-start-2 col-end-3 row-start-3 row-end-4 text-white m-6">
          <Table columns={columns} data={queryData} />
    </div>
  );
});

export default TableSection;

请任何人帮助我解决这个问题。

【问题讨论】:

  • 您希望正文可滚动还是包括表头在内的整个表格?
  • 如果可能的话,我只希望正文可滚动而不是整个表格
  • 我还添加了表格容器的代码,请检查

标签: reactjs react-table react-table-v7


【解决方案1】:

在容器上定义您希望固定高度和可滚动的样式。

maxHeight: "30rem",
overflow: "auto",

【讨论】:

  • 是否可以让表体滚动,而不是表头?
  • 我还添加了表格容器的代码,请检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多