我正在基于可设置的阈值在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()
时,该表不会显示任何数据。
这种单元格样式是基于动态数据的动态条件而不是固定条件发生的吗?
答案 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>
...
</>
);