MUI DataGrid行内按钮调用stopPropagation仍触发onRowClick问题
MUI DataGrid行内按钮点击仍触发行点击事件的解决办法
在MUI DataGrid的行内添加独立操作按钮后,即使在按钮点击事件中调用了stopPropagation和preventDefault,点击按钮时仍会触发行的onRowClick事件,以下是问题原因和解决办法:
问题原因
- MUI的Button组件会渲染嵌套内部元素(如
<span>),点击按钮时event.target可能指向这些子元素,而非按钮本身,导致你在handleRowClick中通过event.target.id === "examinar"的判断失效。 - 按钮点击回调中重复传递事件并调用阻止冒泡方法,逻辑冗余且未完全阻断事件传递链路。
解决方案
方案一:修正行点击事件的目标判断逻辑
修改handleRowClick,使用closest()方法向上查找目标按钮,确保即使点击到按钮内部子元素也能正确识别:
const handleRowClick = (rowData, event) => { const isButtonClick = event.target.closest("#examinar") !== null; if (!isButtonClick) { console.log(rowData.row.url); setSelectedFile(rowData.row.url); } };
方案二:简化按钮点击事件处理
直接在按钮的点击回调中完成阻止冒泡和文件选择逻辑,避免冗余调用:
<button id="examinar" title="Ver" variant="contained" color="primary" style={{ width: "fit-content", zIndex: "30" }} onClick={(e) => { e.stopPropagation(); fileInputRef.current.click(); }} > Select File </button>
方案三:通过getRowProps控制行点击行为
在DataGrid中使用getRowProps替代onRowClick,直接在行的点击逻辑中过滤按钮点击场景:
<DataGrid getRowProps={(params) => ({ onClick: (e) => { if (e.target.closest("#examinar")) return; console.log(params.row.url); setSelectedFile(params.row.url); } })} // 其他原有属性保持不变 >
以上任意一种方案都能实现点击按钮时仅执行文件选择操作,不会触发行的点击事件。
内容的提问来源于stack exchange,提问作者Germán
相关产品推荐
相关产品推荐

