ReactJS + Material-UI:如何缩小Material-UI的<TableRow/>列宽?

11
我目前正在使用ReactJS + Material-UI,使用Material-UI的<Table>时,列宽度会根据内容自动设置。目前看起来所有列都是等宽的,但我想让某些列比其他列宽一些。
那么有什么方法可以任意指定<TableRow>的列宽,并仍然基于内容进行动态调整吗?
3个回答

7
你可以设置TableHeaderColumn及其相应的TableRowColumns的样式。下面我将宽度设置为12像素(背景颜色设置成黄色只是为了更好地演示自定义样式)。
工作的jsFiddle: https://jsfiddle.net/0zh1yfqt/1/
const {
  Table,
  TableHeader,
  TableHeaderColumn,
  TableBody,
  TableRow,
  TableRowColumn,
  MuiThemeProvider,
  getMuiTheme,
} = MaterialUI;

 class Example extends React.Component {
  render() {
    const customColumnStyle = { width: 12, backgroundColor: 'yellow' };

    return (
      <div>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHeaderColumn>A</TableHeaderColumn>
              <TableHeaderColumn style={customColumnStyle}>B</TableHeaderColumn>
              <TableHeaderColumn>C</TableHeaderColumn>
            </TableRow>            
          </TableHeader>
          <TableBody>
            <TableRow>
              <TableRowColumn>1</TableRowColumn>
              <TableRowColumn style={customColumnStyle}>2</TableRowColumn>
              <TableRowColumn>3</TableRowColumn>
            </TableRow>
            <TableRow>
              <TableRowColumn>4</TableRowColumn>
              <TableRowColumn style={customColumnStyle}>5</TableRowColumn>
              <TableRowColumn>6</TableRowColumn>
            </TableRow>
            <TableRow>
              <TableRowColumn>7</TableRowColumn>
              <TableRowColumn style={customColumnStyle}>8</TableRowColumn>
              <TableRowColumn>9</TableRowColumn>
            </TableRow>
          </TableBody>
        </Table>
      </div>
    );
  }
}

const App = () => (
  <MuiThemeProvider muiTheme={getMuiTheme()}>
    <Example />
  </MuiThemeProvider>
);

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

1
但那是硬编码的宽度,是吧?我正在寻找一个可以根据内容动态改变但仍比其他列宽的宽度的选项。 - user2426823
您还可以使用 whiteSpace: 'nowrap',以及 minWidth/maxWidth。 - Jeff McCloud
你能展示完整的代码以及空格吗? - user2426823
您的内容是单行文本还是可以换行呢? - Jeff McCloud
你能展示两种情况吗?因为当窗口被最小化时,内容实际上会被换行。 - user2426823
如果您不想换行,只需执行以下操作:const customColumnStyle = { width: 12, backgroundColor: 'yellow', whiteSpace: 'nowrap' }; 如果您确实希望它换行,但仅在宽度相当大时,请添加“maxWidth: 400”或您想要限制宽度的像素宽度。 - Jeff McCloud

2

<Table>组件中有一个隐藏的属性,使其表现类似于HTML的<table>元素,即根据内容自适应列宽:

<Table style={{ tableLayout: 'auto' }} fixedHeader={false} ...>
    ...
</Table>

虽然不能分别样式每一列,但至少默认情况下对于少量内容的大型列来说不太丑陋。


1
这很棒,但要注意如果表格变得太宽/窗口变得太窄,它也会导致表格溢出屏幕边缘并变得不可见。更有趣的评论在此线程中。 - Lane Rettig

-1
根据 @François Zaninotto 和 @Lane Rettig 的回答。

...

而且,通过这样做,你可以得到一个具有无限列的滚动表格...
componentDidMount() {
    let tbody = $(this.refs.table)
    if (tbody && tbody.length == 1) {
        let div = tbody[0].refs.tableDiv
        div.style.overflowX = 'auto'
        div.parentElement.style.overflowX = 'hidden'
    } else {
        // error handling
    }
}

这与列宽无关。 - opticyclic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接