我目前正在使用ReactJS + Material-UI,而使用Material-UI的<Table>
,列宽会根据内容自动设置。目前它似乎在所有列上强制执行相等的宽度,但我希望某些列占用更多宽度。
那么有没有办法随意指定<TableRow>
列的宽度,而仍然是基于内容的动态?
答案 0 :(得分: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 :(得分:1)
<Table>
组件中有一个隐藏道具,使其行为类似于HTML <table>
元素,即将列宽调整为内容:
<Table style={{ tableLayout: 'auto' }} fixedHeader={false} ...>
...
</Table>
它不会让您逐个设置列的样式,但至少它对于小内容的默认情况下不如大列那么难看。
答案 2 :(得分: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
}
}