我正在尝试向 MUI DataGrid 中的行添加额外的组件。
例如,在下面的DataGrid中,我想在一行的主要内容下方添加一些文本。 (注意行 ID 5 的名字列的值)
是否有可用的 API 允许进行此类修改而无需修改核心组件?如果没有,我如何创建一个允许这种行为的自定义组件?
您可以在字段中使用
renderCell
属性。在返回中,您可以像平常一样编写组件。
const columns = [
{ field: "id", headerName: "ID", width: 90 },
{
field: "firstName",
headerName: "First name",
width: 150,
editable: true,
renderCell: (params) => {
return (
<Stack>
<span>{params.value}</span>
<span>Your extra text</span>
</Stack>
);
}
},
...
]
这是基于您的代码的工作codesandbox
renderCell
的功能仅限于细胞。
如果您的问题更笼统且需要更多自定义:
如何在 DataGrid MUI 中将每一行自定义为 React 组件?
使用
<DataGrid slots={{ row: ProjectInfoRcompDto }}
其中
ProjectInfoRcompDto
是您的 自定义 React 组件
props
类型的 GridRowProps
props.row
使您可以访问 每一行(即:arr_ProjectInfo
中 <DataGrid rows={arr_ProjectInfo}
的每一行)-
row
的默认值为GridRow
——即:slots={{ row: GridRow }}
)
class ProjectInfo {
public readonly name: string;
public readonly arr_urlStr: string[] = [];
public readonly arr_imgInfo: ImgInfo[] = [];
public readonly arr_pathStr_vid: string[] = [];
public readonly flexGrow = 1;
public readonly seqAddedDate;
public readonly lvOfComplexity;
...
const arr_ProjectInfo_ori: readonly ProjectInfo[] = [
...
function App() {
const [arr_ProjectInfo, set_arr_ProjectInfo] = React.useState(arr_ProjectInfo_ori.slice());
return (
<ThemeProvider theme={muitheme_DataGrid}>
<Box>Full Stack Developer / Data Analyst</Box>
<DataGrid
rows={arr_ProjectInfo}
columns={columns}
getRowId={(row) => row.name}
// columns={columns.map((column) => ({
// ...column,
// // renderCell: (params) => <ProjectInfoRcomp projectInfo={params} />,
// renderCell: (params) => <div>8888888{params.value}</div>,
// }))}
// slots={{ row: GridRow }}
slots={{ row: ProjectInfoRcompDto }}
sx={{
margin: 2,
height: '100%',
}}
/>
</ThemeProvider>
);
}
// no_knowlres // check the jsdoc found default GridRow -> GridRowProps
const ProjectInfoRcompDto: React.FC<GridRowProps> = (props) => {
// console.log(props);
// console.log(props.row);
if (!(props.row instanceof ProjectInfo)) {
console.log('not_sure_Api');
// throw new TypeError('not_sure_Api');
return <div>not_sure_Api</div>;
}
return <ProjectInfoRcomp projectInfo={props.row} />;
};