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
相关产品推荐
相关产品推荐

