You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TypeScript为AgGridReact组件绑定useRef时出现重载匹配错误

解决AgGridReact与useRef的TypeScript重载匹配错误

问题根源

错误核心在于:useRef未初始化时,current的类型为undefined,但AgGridReact的Ref属性要求current必须是组件实例或null,两者类型不兼容导致重载匹配失败。

修复方案

方案1:修正Ref初始化

将useRef初始值设为null,并在访问时添加空值检查:

import { AgGridReact } from "ag-grid-react";
import { ColDef } from "ag-grid-community";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";

// 初始化ref为null,明确类型
const gridRef = useRef<AgGridReact>(null);

const onGridReady = () => {
  // 使用可选链避免空值报错
  gridRef.current?.api.sizeColumnsToFit();
};

return (
  <>
    <CommonTitle> Create a new project </CommonTitle>
    <div className="ag-theme-alpine" style={{ height: "80vh" }}>
      <AgGridReact
        ref={gridRef}
        rowData={rowData}
        onGridReady={onGridReady}
        columnDefs={columnDefs}
        defaultColDef={defaultColDef}
        animateRows={true}
      />
    </div>
  </>
);

方案2:直接使用onGridReady参数(无需Ref)

如果仅需调用sizeColumnsToFit,可直接从事件参数中获取API,完全避免使用Ref:

import { AgGridReact } from "ag-grid-react";
import { ColDef, GridReadyEvent } from "ag-grid-community";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";

// 无需定义gridRef
const onGridReady = (params: GridReadyEvent) => {
  params.api.sizeColumnsToFit();
};

return (
  <>
    <CommonTitle> Create a new project </CommonTitle>
    <div className="ag-theme-alpine" style={{ height: "80vh" }}>
      <AgGridReact
        rowData={rowData}
        onGridReady={onGridReady}
        columnDefs={columnDefs}
        defaultColDef={defaultColDef}
        animateRows={true}
      />
    </div>
  </>
);

说明

  • 方案1适用于需要通过Ref调用其他Grid API的场景;
  • 方案2更简洁,适合仅需在Grid就绪时执行单一操作的场景。

内容的提问来源于stack exchange,提问作者Lindaaa asd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 01:45:31