基于动态条件的 ag-grid 单元样式
ag-grid cell style based on dynamic condition
我正在根据设置的table 阈值寻找 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()
时 table 不显示任何数据。
有没有什么方法可以根据动态数据的动态条件而不是固定条件来设置此单元格样式?
您可以使用 AgGrid 的 context
来更新动态值,然后可以使用该值在网格周围传递。以下是如何在 cellStyle
回调中引用 context
对象。
{
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 store 或 API 响应中获取。在下面的演示代码中,您可以使用 input
.
中的值在本地更新 threshold
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>
...
</>
);
现场演示
我正在根据设置的table 阈值寻找 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()
时 table 不显示任何数据。
有没有什么方法可以根据动态数据的动态条件而不是固定条件来设置此单元格样式?
您可以使用 AgGrid 的 context
来更新动态值,然后可以使用该值在网格周围传递。以下是如何在 cellStyle
回调中引用 context
对象。
{
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 store 或 API 响应中获取。在下面的演示代码中,您可以使用 input
.
threshold
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>
...
</>
);