You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置Material-UI表格表头为单行显示不自动换行

解决方案

方案1:使用Material UI自带属性实现(推荐)

  • 给所有表头的TableCell组件添加nowrap属性,该属性会自动为单元格添加white-space: nowrap样式,强制内容单行显示
  • 在外层的TableContainer组件上添加样式overflowX: 'auto',开启横向滚动条适配超出屏幕宽度的表格内容

可直接复用的代码示例:

import React 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 TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const useStyles = makeStyles({
  table: {
    minWidth: 700, // 可根据表头实际总宽度调整最小值,避免表格被挤压变形
  },
});

function createData(name, calories, fat, carbs, protein) {
  return { name, calories, fat, carbs, protein };
}

const rows = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

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

  return (
    <TableContainer component={Paper} style={{ overflowX: 'auto' }}>
      <Table className={classes.table} aria-label="simple table">
        <TableHead>
          <TableRow>
            {/* 所有表头单元格添加nowrap属性 */}
            <TableCell nowrap>Dessert (100g serving)</TableCell>
            <TableCell align="right" nowrap>Calories</TableCell>
            <TableCell align="right" nowrap>Fat&nbsp;(g)</TableCell>
            <TableCell align="right" nowrap>Carbs&nbsp;(g)</TableCell>
            <TableCell align="right" nowrap>Protein&nbsp;(g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row) => (
            <TableRow key={row.name}>
              <TableCell component="th" scope="row">
                {row.name}
              </TableCell>
              <TableCell align="right">{row.calories}</TableCell>
              <TableCell align="right">{row.fat}</TableCell>
              <TableCell align="right">{row.carbs}</TableCell>
              <TableCell align="right">{row.protein}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}

方案2:自定义CSS实现(适合需要额外定制的场景)

如果需要同时实现超出截断显示省略号等自定义效果,可以手动写样式注入到表头单元格:

  • 给表头TableCell添加自定义类名,设置如下CSS规则即可:
.table-header-cell {
  white-space: nowrap;
  /* 可选配置:超出指定宽度显示省略号
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
  */
}
  • 同样需要在外层TableContainer开启横向滚动,逻辑和方案1完全一致。

内容的提问来源于stack exchange,提问作者kumbhani bhavesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:27:04