Material-table: 如何改变列的宽度?

Material-table: How change width of the columns?

我正在使用 Google Material UI 官方推荐的 Material Table 库作为数据 table 库并且在配置时遇到问题列的宽度。

width 属性 列正在工作,直到我们的内容适合单元格:CodeSandbox 有解决办法吗?

如果你想为每一列设置特定的宽度,我相信你需要指定选项 tableLayout: 'fixed'docs 是这样引用它的:

tableLayout | auto or fixed | To make columns width algorithm auto or fixed

所以你的代码可能是这样的:

 const tableColumns = [
    { title: "Lorem ipsum", field: "lorem", width: "10%" }, // fixed column width
    { title: "Name", field: "name", width: "80%" },
    { title: "Custom status", field: "customStatus", width: "10%" }]


 <MaterialTable
    tableRef={tableRef}
    columns={tableColumns}
    data={tableData}
    onRowClick={(evt, selectedRow) =>
      setSelectedRow(selectedRow.tableData.id)
    }
    title="Remote Data Example"
    options={{
      rowStyle: rowData => ({
        backgroundColor:
          selectedRow === rowData.tableData.id ? "#EEE" : "#FFF"
      }),
      tableLayout: "fixed"
    }}
  />

这里是 sandbox.

祝你好运!

为动态列宽使用以下样式,header

        columns={[
          {
            title: 'Create Date',
            field: 'create_date',
            cellStyle: {
             whiteSpace: 'nowrap'
            },
           ...
           ]}
        options={{
          headerStyle: {
            backgroundColor: '#DEF3FA',
            color: 'Black',
             whiteSpace: 'nowrap'
          },
           ...
         }
此处发布的

None 解决方案适用于最新版本的 material-table(撰写本文时为 v1.69.3),因此我创建了一个 codesandbox 测试不同的设置组合,直到找到最适合我的设置。

<MaterialTable
  columns={[
    { title: "Name", field: "name" },
    { title: "Email", field: "email" },
    {
      title: "Status",
      field: "status",
      cellStyle: {
        cellWidth: '15%'
      }
    }
  ]}
  data={users}
  options={{
    tableLayout: 'auto'
  }}
/>

我自己也一直在为同样的问题而苦苦挣扎,none 这里提供的解决方案对我有用,所以我会离开我的,以防有人发现它有帮助。它有点老套,但我发现它是唯一适用于我的页面设置的。我什至尝试粘贴 docs 中的示例,因为它在某些列上具有固定宽度,但这在我的页面上也不起作用。

<MaterialTable
  title="Users"
  options={{
    rowStyle: {
      overflowWrap: 'break-word'
    }
  }}
  columns={[
    { 
      title: "Name",
      field: "name",
      cellStyle: {
        minWidth: 200,
        maxWidth: 200
      }
    }
  ]},
  data={userData}
/>

什么对我很有效

<MaterialTable
  title="Users"
  options={{
    rowStyle: {
      overflowWrap: 'break-word'
    }
  }}
  columns={[
    { 
      title: "Name",
      field: "name",
      width: "4%"
    }
  ]},
  data={userData}
/>