基于动态条件的网格网格样式

时间:2020-09-20 05:57:30

标签: reactjs ag-grid ag-grid-react

我正在基于可设置的阈值在ag-grid中动态地绘制单元格,在该阈值之上,该单元格变为绿色,否则为红色。

我尝试了以下操作:

<AgGridReact
  onGridReady={onGridReady}
  pagination={true}
  columnDefs={[
    { headerName: "SYMBOL", field: "symbol" },
    {
      headerName: "PRICE",
      field: "price",
      volatile: true,
      cellStyle: function (params) {
        if (params.value < threshold) {
          return { backgroundColor: "red" };
        } else {
          return { backgroundColor: "green" };
        }
      }
    }
  ]}
/>

并输入阈值(设置状态)。但是,即使状态发生了变化,columnDefs也没有发生变化。

我正在使用.applyTransactionAsync()进行高频更新。因此,在使用.setColumnDefs()时,该表不会显示任何数据。

这种单元格样式是基于动态数据的动态条件而不是固定条件发生的吗?

1 个答案:

答案 0 :(得分:1)

您可以使用AgGrid的context更新动态值,然后将其用于传递网格。这是在context回调中引用cellStyle对象的方式。

{
  headerName: "PRICE",
  field: "price",
  cellStyle: (params) => {
    if (params.value < params.context.threshold) {
      return { backgroundColor: "lightCoral" };
    } else {
      return { backgroundColor: "deepSkyBlue" };
    }
  }
}

设置context很简单

<AgGridReact
  columnDefs={columnDefs}
  rowData={rowData}
  context={{
    threshold
  }}
  ...
/>

其中threshold是一个动态值,您可以从redux存储或API响应中获取。在下面的演示代码中,您可以使用threshold中的值在本地更新input

const [threshold, setThreshold] = React.useState(20);
const updateThreshold = () => {
  const inputEl = document.getElementById("thresholdInput");
  const newValue = parseFloat((inputEl as HTMLInputElement).value);
  setThreshold(newValue);
};

return (
  <>
    <input id="thresholdInput" defaultValue={threshold} />
    <button onClick={updateThreshold}>Update threshold</button>
    ...
  </>
);

实时演示

Edit 63975972/ag-grid-cell-style-based-on-dynamic-condition