React Ag-Grid v28列按钮渲染器的TypeScript类型问题解决
解决React Ag-Grid v28自定义actionCellRenderer的TypeScript类型问题
问题
在React Ag-Grid v28中实现自定义列的编辑按钮时,自定义actionCellRenderer函数的params参数缺少类型定义,导致TypeScript抛出Parameter 'params' implicitly has an 'any' type错误。查看ColDef类型定义发现cellRendererParams被标注为any,但不想用any绕过类型检查,需要正确的类型定义方案。
解决方案
Ag-Grid提供了ICellRendererParams<TData>类型来定义单元格渲染器的参数,其中TData是你的行数据类型,使用这个类型可以获得完整的类型提示,同时避免any带来的类型安全问题。
1. 定义行数据类型
首先为你的行数据创建类型接口,以示例中的奥运选手数据为例:
interface OlympicWinner { athlete: string; age: number; country: string; year: number; sport: string; gold: number; silver: number; bronze: number; }
2. 为params指定类型
从ag-grid-community导入ICellRendererParams,并为actionCellRenderer的params参数指定该类型:
import { ICellRendererParams } from "ag-grid-community"; function actionCellRenderer(params: ICellRendererParams<OlympicWinner>) { // 原有逻辑保持不变 }
3. 完善组件内其他类型定义
为rowData和columnDefs也指定对应类型,提升整个组件的类型严谨性:
const [rowData, setRowData] = useState<OlympicWinner[]>(); const [columnDefs, setColumnDefs] = useState<ColDef<OlympicWinner>[]>([ // 列定义内容不变 ]);
完整修改后的代码
import React, { useState, useEffect } from "react"; import 'ag-grid-community/styles/ag-grid.css'; import 'ag-grid-community/styles/ag-theme-alpine.css'; import { AgGridReact } from "ag-grid-react"; import { ICellRendererParams, ColDef } from "ag-grid-community"; interface OlympicWinner { athlete: string; age: number; country: string; year: number; sport: string; gold: number; silver: number; bronze: number; } const UserList: React.FC = () => { const [rowData, setRowData] = useState<OlympicWinner[]>(); function actionCellRenderer(params: ICellRendererParams<OlympicWinner>) { let eGui = document.createElement("div"); let editingCells = params.api.getEditingCells(); let isCurrentRowEditing = editingCells.some((cell) => { return cell.rowIndex === params.node.rowIndex; }); if (isCurrentRowEditing) { eGui.innerHTML = ` <button class="action-button update" data-action="update"> update </button> <button class="action-button cancel" data-action="cancel"> cancel </button> `; } else { eGui.innerHTML = ` <button class="action-button edit" data-action="edit"> edit </button> <button class="action-button delete" data-action="delete"> delete </button> `; } return eGui; } const [columnDefs, setColumnDefs] = useState<ColDef<OlympicWinner>[]>([ { field: 'athlete', filter: false, minWidth: 150, editable: true }, { field: 'age', filter: false, maxWidth: 90, editable: true }, { headerName: "action", minWidth: 150, cellRenderer: actionCellRenderer, editable: false, colId: "action" } ]); useEffect(() => { fetch('https://www.ag-grid.com/example-assets/olympic-winners.json') .then(result => result.json()) .then(rowData => setRowData(rowData)) }, []); return ( <div> <AgGridReact rowData={rowData} columnDefs={columnDefs} /> </div> ) } export default UserList;
内容的提问来源于stack exchange,提问作者senko
相关产品推荐
相关产品推荐

