ag-grid建议在需要时,在他们的onGridReady回调中获取指向网格API的指针作为变量。使用 React 类,你可以这样做:
class MyGrid extends React.Component {
...
onGridReady = params => {
this.gridApi = params.api;
}
render() {
// on subsequent calls still have this.gridApi...
return <AgGridReact onGridReady={this.onGridReady} ... />;
}
}
使用反应钩子执行此操作的正确模式是什么? 这是我到目前为止的代码;
const MyGrid = props => {
let gridApi = null;
const onGridReady = params => {
gridApi = params.api;
}
return <AgGridReact onGridReady={onGridReady} ... />;
}
问题是"MyGrid"组件函数将被调用多次,并且在onGridReady函数运行后一次,在我使用它之前将变量重置为null。
我应该在上面的范围内使变量全局化吗?
let gridApi = null;
const MyGrid = props => { ... }
或者这是像"useMemo"这样的东西的一个很好的用例吗?
使用这个钩子:
import { useCallback, useState } from 'react';
export default function useAgGrid() {
const [gridApi, setGridApi] = useState();
const onGridReady = useCallback(
(params) => {
const { api, columnApi } = params;
setGridApi({ api, columnApi });
},
[]
);
return {
onGridReady,
...gridApi && gridApi
};
}
为什么需要引用网格 api?您是否查看了本指南的反应 16+ https://www.ag-grid.com/react-data-grid/react-hooks/?将 react refs
与 useRef
一起使用也是一个不错的选择。