![](/img/trans.png)
[英]Can a cellRenderer function in ag-Grid return a React component?
[英]AG-Grid & React Hooks: How to call a function in a parent component from a cellRendererFramework component?
我正在做一个使用 ag-grid 25.1.0 的项目,它无法更新到更高版本。 该项目的数据以卡片或网格的形式呈现在 2 个视图中,因此数据必须存储在父组件中并通过子组件向下传递。 我的问题是我不知道如何从网格中的按钮调用父组件中的 function。 来自父级的流程是:parent > grid > columnDefs > cellRendererFramework,我需要从该列表的最后一个元素调用父级中的 setAgentData。 项目中有很多定制代码,所以我在这里添加了一个非常简化的版本,省略了与问题不直接相关的任何内容。
父组件:
import Grid from './grid/grid';
....
const Apps = (props) => {
const [agentData, setAgentData] = useState(props.data);
return (
<Grid
agentData={agentData}
setAgentData={setAgentData}
/>
);
};
export default Apps;
网格组件:
import { columnDefs } from './columns';
import Grid from 'ag-grid';
...
const Grid = (props) => {
...
return (
<Grid
columnDefs={columnDefs}
records={props.agentData}
setAgentData={props.setAgentData} // Unsure if this is how to pass the function call here
/>
);
};
export default Grid;
列定义组件:
import Toggle from './toggle';
...
export const columnDefs = [
{
field: 'active',
cellRendererFramework: Toggle,
// Unsure how to pass the function call here
...
}
]
CellRendererFramework 组件:
const Toggle = (props) => {
...
return (
<button
type="button"
value="props.agentData"
onClick={() => props.setAgentData(!props.agentData)
/>
);
};
export default Toggle;
正如我所说,这是一个非常简化的代码版本——我只需要知道如何从 Toggle 组件调用 setAgentData。 如果我在其他地方犯了任何错误,请忽略它们
要在Toggle
中访问setAgentData
,您需要将其作为道具传递。 ag-grid 允许您通过将cellRendererParams
属性添加到对象来指定要在对象的columnDefs
数组中传递的附加参数。 由于setAgentData
仅在您的Grid
组件中可用,而不是“列定义组件”文件,您可以像这样.map()
您的对象数组以添加cellRendererParams
以通过 function:
const Grid = (props) => {
const columnDefsWithProps = useMemo(() => {
return columnDefs.map(col => col.cellRendererFramework === Toggle
? {...col, cellRendererParams: {setAgentData: props.setAgentData}}
: col
);
}, [props.setAgentData]);
return (
<Grid
columnDefs={columnDefsWithProps}
records={props.agentData}
/>
);
};
export default Grid;
我将上面的内容包装在useMemo()
中,以避免在每次重新渲染Grid
时重新运行 map。 如果您有许多需要将其传递给的网格项目,您可以更改.map()
中的条件。 如果当前不可用,您可能还需要传递其他道具,例如agentData
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.