【问题标题】:How to limit column width on react-admin List View如何限制 react-admin 列表视图的列宽
【发布时间】:2020-05-01 05:43:09
【问题描述】:

在具有少量列的列表视图中,列非常宽。我想至少限制其中一些列的宽度(最后一列除外):

仍在尝试加快 react-admin、react 和 material-ui 的速度。我敢肯定,其中涉及一些样式。有人可以指出我正确的方向吗?谢谢。

更新: 我按照 Jozef 的建议添加了样式,但没有改变。这是 Inspect 中的样子:

【问题讨论】:

    标签: reactjs react-admin


    【解决方案1】:

    有两个选项可以自定义单元格的宽度。

    如果你想均匀设置宽度,你可以改变Datagrid的table-layout

    <Datagrid style={{tableLayout: 'fixed'}} rowClick="edit">
      <TextField source="sourceName" />
      <BooleanField source="active" />
      <TextField source="organizationName" />
    </Datagrid>
    

    如果这还不够,那么我们必须创建自定义的Datagrid 及其所有依赖项,以便我们可以传递给TableCell 组件的特定宽度。无论是百分比还是 px 值。这不是很好documented 所以你必须依赖ra-ui-materialui 中的源代码

    这是一个例子

    import {
      Datagrid,
      DatagridBody,
      DatagridCell,
      TextField,
      BooleanField
     } from 'react-admin';
    import Checkbox from '@material-ui/core/Checkbox';
    import TableCell from '@material-ui/core/TableCell';
    import TableRow from '@material-ui/core/TableRow';
    
    const CustomDatagridRow = ({ record, resource, id, onToggleItem, children, selected, basePath }) => (
        <TableRow key={id}>
            <TableCell style={{width="10%"}} padding="none">
                {record.selectable && <Checkbox
                    checked={selected}
                    onClick={() => onToggleItem(id)}
                />}
            </TableCell>
            {React.Children.map(children, field => (
                <TableCell style={{width: field.props.width}} key={`${id}-${field.props.source}`}>
                    {React.cloneElement(field, {
                        record,
                        basePath,
                        resource,
                    })}
                </TableCell>
            ))}
        </TableRow>
    );
    
    const CustomDatagridBody = props => <DatagridBody {...props} row={<CustomDatagridRow />} />;
    const CustomDatagrid = props => <Datagrid {...props} body={<CustomDatagridBody />} />;
    
    <CustomDatagrid style={{tableLayout: 'fixed'}} rowClick="edit">
      <TextField width="20%" source="sourceName" />
      <BooleanField width="20%" source="active" />
      <TextField width="50%" source="organizationName" />
    </CustomDatagrid>
    

    【讨论】:

    • 感谢您的建议。我尝试了您对 style={{ tableLayout: 'fixed'}} 的建议,它对表格的列宽没有任何影响。抱歉,我的 react 经验有限。
    • 这很奇怪。你确定你把它放在Datagrid 组件中吗?如果你在 chrome 开发工具中检查 html table 标签,你看到它的样式被覆盖了吗?
    • 是的,我按照你说的添加了。我会在我的问题中放一张图片,表明它似乎没有被覆盖???
    • 它被覆盖并且列宽被平均分割。如果您再添加几列,我想您可能会注意到差异
    • 啊,是的,我明白了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-11-16
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    相关资源
    最近更新 更多