我有一个名为的功能组件GenericGrid
import React, { useState } from "react";
import { AgGridReact } from "ag-grid-react";
const GenericGrid = props => {
const [visible, setVisible] = useState(false);
const gridApi = useRef();
const onGridReady = params => {
const { defaultFilter } = props;
gridApi.current = params.api;
const datasource = getServerDataSource(
gridApi.current,
{
size: AppConstants.PAGE_SIZE,
url: baseUrl,
defaultFilter
}
);
gridApi.current.setServerSideDatasource(datasource);
};
... // < == other methods omitted for brevity
const onAddNew = () => setVisible(true);
return (
<>
{!visible && (
<div className="ag-theme-material gridSize">
<AgGridReact
reactNext={true}
onCellValueChanged={onCellValueChanged}
onGridReady={onGridReady}
columnDefs={columnDefs}
pagination={true}
context={GenericGrid} // <== passed the component in context
onSelectionChanged={onRowSelect}
{...props.options}
></AgGridReact>
</div>
)}
{visible &&
clonedElementWithMoreProps(addNewComponent, {
visible,
onHide: () => setVisible(false),
dialogBtnLoading: createNewProgress,
onSubmit: create
})}
</>
);
}
export default GenericGrid;
现在最后一列有一个列定义,cellRendererFramework
如下所示:
if (field.name === "ViewDetails") {
return {
field: field.name,
colId: field.name,
headerName: field.displayName,
sortable: false,
cellRendererFramework: params => {
console.log("params.context", params.context); // <== prints the definition of 'GenericGrid'
console.log('params.context.onAddNew', params.context.onAddNew) // <== but this prints undefined
return (
<button className="btn btn-sm p-0 btn-link text-cm-primary"
onClick={params.context.onAddNew}
>
View Details
</button>
);
}
};
}
现在单击最后一列中的按钮,我想调用函数onAddNew
,如果可能的话,甚至更好地setValue
直接在GenericGrid
组件中声明。
根据官方文档,这适用于class
上下文传递的基于组件,如下所示context = { componentParent: this }
:但是由于我的组件是功能组件,我直接在上下文中传递GenericGrid
,假设它可以工作但它没有。