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

DataGrid组件onRowEditStop阻止Enter默认行为的TypeScript报错

解决DataGrid onRowEditStop中Enter键默认行为阻止的TypeScript类型错误

你遇到的TypeScript报错,是因为onRowEditStop的第二个参数e属于MuiEvent类型,该类型本身并不包含key属性,键盘事件的相关信息需要从e.nativeEvent这个原生事件对象中获取。

修正后的代码

<DataGrid
    rows={sites?.map((site) => ({ ...site, setSites })) || []}
    processRowUpdate={tryCatchWrapper(updateSite)}
    // 修正后的事件处理逻辑
    onRowEditStop={(_, e) => {
      // 通过类型守卫确认原生事件为键盘事件
      if (e.nativeEvent instanceof KeyboardEvent && e.nativeEvent.key === "Enter") {
        e.defaultMuiPrevented = true;
      }
    }}
    columns={columns}
    loading={isLoading}
    editMode="row"
    sx={dataGridStyles[0]}
    disableSelectionOnClick
    experimentalFeatures={{ newEditingApi: true }}
    pageSize={10}
    rowsPerPageOptions={[10]}
/>

核心说明

  • MuiEvent是MUI对原生事件的封装,真实的键盘事件数据存储在nativeEvent属性中
  • 使用instanceof KeyboardEvent做类型守卫,能让TypeScript明确当前事件的类型,消除类型报错
  • 保留e.defaultMuiPrevented = true的逻辑,确保可以正常阻止DataGrid的Enter键默认行为

内容的提问来源于stack exchange,提问作者Sebastian Herrera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:05:32