css - 如何在一行中创建多行表格(Material-UI/CSS)

标签 css reactjs user-interface html-table material-ui

我有这样的数组:

const sample = [
  { name: 'apple', detail: [{'a', 'b'}]},
  { name: 'banana', detail: [{'a', 'b'}]},
];

假设我想创建一个如下附件所示的表格:

enter image description here

那是表体部分,我已经把所有的细节都放在里面了。它正在按照我的预期创建表格,但尺寸真的很窄,而且与表格头部不匹配。

我想知道是否有一种聪明的方法可以将多个数据映射成一行并嵌入到一个表格单元格中。

名称部分(苹果和香蕉)必须是具有行跨度的第一个表格单元格。

最佳答案

您可以在 TableCell 上使用 rowSpan 来做到这一点。只需为其分配一个值 detail.length + 1

在这里,试一试:

import React, { Fragment } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";

const useStyles = makeStyles(theme => ({
  root: {
    width: "100%",
    marginTop: theme.spacing(3),
    overflowX: "auto"
  },
  table: {
    minWidth: 700
  }
}));

const sample = [
  { name: "apple", detail: ["a", "b", "c", "d"] },
  { name: "banana", detail: ["a", "b"] }
];

export default function SpanningTable() {
  const classes = useStyles();

  return (
    <Paper className={classes.root}>
      <Table className={classes.table}>
        <TableHead>
          <TableRow>
            <TableCell>Fruit</TableCell>
            <TableCell align="right">Buyers</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {sample.map(item => (
            <Fragment>
              <TableRow>
                <TableCell rowSpan={item.detail.length + 1}>
                  {item.name}
                </TableCell>
              </TableRow>
              {item.detail.map(detail => (
                <TableRow>
                  <TableCell>{detail}</TableCell>
                </TableRow>
              ))}
            </Fragment>
          ))}
        </TableBody>
      </Table>
    </Paper>
  );
}

Here's a Working Sample CodeSandbox Demo for your ref.

关于css - 如何在一行中创建多行表格(Material-UI/CSS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57318230/

相关文章:

html - css 中的 svg sprite - 是变换比例缩放的合法方式

html - 显示: inline的实际目的是什么

html - CSS帮助气泡居中箭头和气泡与文本对齐

javascript - 无法在 react-redux-form 控件中包装 react-autocomplete 元素

iphone - 将 View Controller 推送到导航 Controller 时 UI 阻塞

macos - 适用于 Mac 的 UI 素描软件

html - 将上下文类应用于导航栏中的列表项

javascript - npm run build 时显示错误

javascript - React + Meteor + Bootstrap Modal 管理数据

python - cx_freeze 中的 TCL_LIBRARY