Ag Grid如何覆盖agAnimateShowChangeCellRenderer的样式与超时
自定义agAnimateShowChangeCellRenderer动画超时与样式方案
内置agAnimateShowChangeCellRenderer的1秒动画超时是硬编码实现,没有提供直接修改的配置入口,要调整超时时间、自定义样式可以按以下方法实现:
方案:自定义可配置的动画单元格渲染器
这个方案可以灵活配置任意列的动画时长,同时支持自定义样式,是官方推荐的扩展方式。
- 首先实现自定义渲染器,支持传入自定义超时参数:
class CustomAnimateCellRenderer { init(params) { // 默认动画时长2秒,可通过cellRendererParams自定义 this.animationDuration = params.animationTimeout ?? 2000; this.eGui = document.createElement('span'); this.lastValue = params.value; this.renderValue(params); } getGui() { return this.eGui; } refresh(params) { if (params.value === this.lastValue) return true; // 清除旧动画状态 if (this.timer) clearTimeout(this.timer); this.eGui.classList.remove( 'ag-value-change-up', 'ag-value-change-down', 'ag-value-change-highlight' ); // 渲染新值 this.renderValue(params); // 值变化时添加对应动画类 if (this.lastValue !== undefined && this.lastValue !== null) { const changeClass = params.value > this.lastValue ? 'ag-value-change-up' : 'ag-value-change-down'; this.eGui.classList.add(changeClass, 'ag-value-change-highlight'); // 按配置的时长移除动画类 this.timer = setTimeout(() => { this.eGui.classList.remove( 'ag-value-change-up', 'ag-value-change-down', 'ag-value-change-highlight' ); }, this.animationDuration); } this.lastValue = params.value; return true; } renderValue(params) { this.eGui.innerText = params.valueFormatted ? params.valueFormatted(params.value) : params.value; } destroy() { if (this.timer) clearTimeout(this.timer); } }
- 在Grid配置中注册自定义渲染器:
const gridOptions = { columnDefs: columnDefs, // 注册自定义组件 components: { customAnimateCellRenderer: CustomAnimateCellRenderer }, // 其余原有配置保持不变 };
- 替换列定义中的原生渲染器,可单独为每列配置不同的动画时长:
{ field: 'current', width: 200, aggFunc: 'sum', enableValue: true, cellClass: 'number', valueFormatter: numberCellFormatter, // 替换为自定义渲染器 cellRenderer: 'customAnimateCellRenderer', // 单独配置该列动画时长为3秒 cellRendererParams: { animationTimeout: 3000 } }
自定义动画样式
直接覆盖动画类的CSS即可修改默认样式,不需要改动渲染器逻辑:
/* 数值上涨样式 */ .ag-value-change-up { color: #10b981; padding-left: 4px; position: relative; } .ag-value-change-up::before { content: '↑'; position: absolute; left: -12px; } /* 数值下跌样式 */ .ag-value-change-down { color: #ef4444; padding-left: 4px; position: relative; } .ag-value-change-down::before { content: '↓'; position: absolute; left: -12px; } /* 高亮过渡效果 */ .ag-value-change-highlight { background-color: rgba(250, 204, 21, 0.25); transition: all 0.25s ease; }
注意事项
- 自定义渲染器的
destroy方法必须清除定时器,避免内存泄漏 - 如果不需要逐列配置不同时长,直接在渲染器里写死固定超时值即可,不用传
cellRendererParams - 原有列的
valueFormatter、cellClass等配置完全不需要修改,和原生渲染器逻辑兼容
内容的提问来源于stack exchange,提问作者Bozhinovski
相关产品推荐
相关产品推荐

