ReactJS + Material-UI:如何减少Material-UI的列宽 ?

问题描述 投票:8回答:3

我目前正在使用ReactJS + Material-UI,而使用Material-UI的<Table>,列宽会根据内容自动设置。目前它似乎在所有列上强制执行相等的宽度,但我希望某些列占用更多宽度。

那么有没有办法任意分配<TableRow>列的宽度,仍然是基于内容的动态?

javascript html css reactjs material-ui
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
投票

<Table>组件中有一个隐藏的prop,它使其行为类似于HTML <table>元素,即使列宽度适应内容:

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

它不允许您逐个设置列的样式,但至少它默认情况下比小内容的大列更难看。


0
投票

根据@FrançoisZaninotto@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
    }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.