创建一个按钮来降低或增加 ag-grid 中的列宽

Create a button that lowers or increases the column width in ag-grid

我正在尝试创建两个按钮,一个增加 ag-grid 中的列宽,另一个按钮在单击时减小列宽。

您可以使用 ColumnApi.getColumnState() and update any columns width using ColumnApi.setColumnWidth() 获取最新的列宽。这是一个例子

const changeWidth = (colId, offset) => () => {
  const currentWitdth = columnApi
    .getColumnState()
    .find((c) => c.colId === colId).width;
  columnApi.setColumnWidth(colId, currentWitdth + offset);
};

如果你想改变所有列的宽度

const changeAllWidth = (offset) => () => {
  const columnState = columnApi.getColumnState();

  columnState.forEach((c) => {
    if (c.width) {
      columnApi.setColumnWidth(c.colId, c.width + offset);
    }
  });
};

用法

<button onClick={changeAllWidth(10)}>+ All</button>
<button onClick={changeAllWidth(-10)}>- All</button>

<button onClick={changeWidth("athlete", 10)}>+ athlete</button>
<button onClick={changeWidth("athlete", -10)}>- athlete</button>
<button onClick={changeWidth("age", 10)}>+ age</button>
<button onClick={changeWidth("age", -10)}>- age</button>

现场演示