【问题标题】:How to set smallest width on table column in Material-UI?如何在 Material-UI 中设置表格列的最小宽度?
【发布时间】:2020-11-14 17:03:22
【问题描述】:

我正在使用 Material-UI 在 React 中构建一个网站。我有一张表格,想知道是否可以设置列宽以适应数据+两端的一些额外填充?

这是我的桌子:

  <Table className={classes.table} size="small">
    <TableHead>
      <TableRow>
        <TableCell width="???">CA</TableCell> <--- Width should be as much as "Fit to data" + margin of X pixels
        <TableCell width="140px">CB</TableCell>
        <TableCell width="240px">CC</TableCell>
        <TableCell width="200px">CD</TableCell>
        <TableCell>CE</TableCell>
      </TableRow>
    </TableHead>
    <TableBody>
      {data.map((row) => (
        <TableRow key={row.id}>
          <TableCell>{row.ca}</TableCell>
          <TableCell>{row.cb}</TableCell>
          <TableCell>{row.cc}</TableCell>
          <TableCell>{row.cd}</TableCell>
          <TableCell>{row.ce}</TableCell>
        </TableRow>
      ))}
    </TableBody>
  </Table>

我希望CA 列最小化,这样它就可以在两边留出额外的空间来容纳数据,这样内容就不会触及列边界。

我试过了:

  1. 根本没有声明 width - 没用
  2. width="auto" - 没用

【问题讨论】:

    标签: javascript css reactjs material-ui


    【解决方案1】:

    您可以使用 css 定位此 th 并将其设置为 width: 1px; white-space: nowrap;

    我认为这应该适用于您的情况:

    .MuiTableCell-head:first-child {
       width: 1px;
       white-space: nowrap;
    }
    
    

    下面是使用 react inline-styling 实现这一点的方法:

    // You can also add padding or any other style props to this style object 
    
    <TableCell style={{width: '1px', whiteSpace: 'nowrap'}}>CA</TableCell>
    
    

    【讨论】:

    • 谢谢,你能再具体一点吗?我正在使用 javascript 样式(不是 css)
    • @AdamWojnar - 我编辑了我的答案并添加了一个内联样式示例。让我知道这是否有效。
    猜你喜欢
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多