如何禁用React MUI DataGrid指定单元格的复选框选择功能
解决方案
只需要在Total marks列的Link组件上添加点击事件阻止冒泡即可,点击链接时事件不会向上传递到表格单元格,也就不会触发行选中逻辑,其余单元格的点击选中能力完全不受影响。
核心修改点
在Link组件上增加onClick回调,调用事件的stopPropagation方法:
<Link target="_blank" rel="noopener noreferrer" href="https://www.google.com/" sx={{ cursor: "pointer" }} onClick={(e) => e.stopPropagation()} > {cellValues.value} </Link>
修改后完整代码
import * as React from "react"; import { DataGrid } from "@mui/x-data-grid"; import Link from "@mui/material/Link"; const getTotal = (params) => params.getValue(params.id, "maths") + params.getValue(params.id, "science"); const columns = [ { field: "maths", headerName: "Maths", width: 130 }, { field: "science", headerName: "Science", width: 130 }, { field: "Total", headerName: "Total marks", width: 160, valueGetter: getTotal, editable: true, renderCell: (cellValues) => ( <Link target="_blank" rel="noopener noreferrer" href="https://www.google.com/" sx={{ cursor: "pointer" }} onClick={(e) => e.stopPropagation()} > {cellValues.value} </Link> ) } ]; const rows = [ { id: 1, maths: 75, science: 60 }, { id: 2, maths: 80, science: 70 }, { id: 3, maths: 50, science: 80 }, { id: 4, maths: 80, science: 60 }, { id: 5, maths: 100, science: 90 } ]; export default function ValueGetterGrid() { return ( <div style={{ height: 400, width: "100%" }}> <DataGrid rows={rows} columns={columns} checkboxSelection /> </div> ); }
方案原理
DataGrid的行点击选中逻辑是绑定在单元格/行元素上的,点击内部元素时事件会逐层向上冒泡触发父元素的点击事件。调用stopPropagation可以终止事件冒泡,只有链接本身的跳转逻辑会触发,不会触发上层的行选中逻辑。
内容的提问来源于stack exchange,提问作者FD3
相关产品推荐
相关产品推荐

