如何更新Ag Grid React自定义状态栏组件接收的Props
问题根因
AG Grid 的状态栏配置属于初始化静态配置,初始化完成后再修改 statusPanelParams 中的参数,AG Grid 不会主动同步到已渲染的自定义状态栏组件,因此父组件的 total 状态更新后,状态栏组件接收不到最新的 prop,自然不会触发重渲染。
解决方案
有两种常用的实现方式,第二种更贴合你「过滤时更新总行数」的实际业务需求:
方案1:通过 AG Grid 响应式 Context 传递动态值
AG Grid 提供的 context 属性支持响应式更新,修改后会自动同步给所有自定义框架组件:
- 给
AgGridReact组件添加context属性,将动态的total传入:
<AgGridReact rowData={rowData} frameworkComponents={{ customStatusBar: CustomStatusBar }} statusBar={{ statusPanels: [ { statusPanel: 'customStatusBar', align: 'center' } ] }} {/* 新增context传递动态值 */} context={{ total }} >
- 自定义状态栏组件从
props.context中取值即可:
const CustomStatusBar = props => { return ( <div className="ag-status-bar-center"> <div className="ag-status-name-value ag-status-panel ag-status-panel-total-row-count"> <span className="label">Total Rows</span>: <span className="ag-status-name-value-value">{props.context.total}</span> </div> </div> ); };
方案2:直接通过 Grid API 监听过滤事件获取行数
不需要手动维护 total 状态,直接在状态栏组件内监听表格事件自动更新,更适配过滤场景:
import React, { useState, useEffect } from 'react'; const CustomStatusBar = props => { const [total, setTotal] = useState(0); useEffect(() => { // 更新行数的方法,getDisplayedRowCount会自动返回过滤后的可见行数 const updateRowCount = () => { setTotal(props.api.getDisplayedRowCount()); }; // 初始化计算行数 updateRowCount(); // 监听表格模型更新事件(过滤、排序、行数据变更都会触发) props.api.addEventListener('modelUpdated', updateRowCount); // 组件卸载时移除事件监听避免内存泄漏 return () => props.api.removeEventListener('modelUpdated', updateRowCount); }, [props.api]); return ( <div className="ag-status-bar-center"> <div className="ag-status-name-value ag-status-panel ag-status-panel-total-row-count"> <span className="label">Total Rows</span>: <span className="ag-status-name-value-value">{total}</span> </div> </div> ); };
这种方式不需要修改父组件的状态逻辑,表格过滤、排序、行数据变更时都会自动更新状态栏的行数展示。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

