如何在MUI Data Grid列中正确渲染按钮或图标?
解决MUI DataGrid操作列渲染图标/按钮显示
[object object]的问题 直接把React组件塞到rows数组里,或者用模板字符串转成字符串,都会导致DataGrid渲染出[object object]——因为DataGrid默认会把字段值当成纯文本处理,而React组件本质是对象,转字符串就会变成这个结果。正确的做法是在列配置里通过render属性自定义渲染内容,把渲染逻辑和数据分开。
修改后的完整代码
import React from 'react' import { DataGrid } from '@mui/x-data-grid' import { useNavigate } from 'react-router-dom' import EditIcon from '@mui/icons-material/Edit' import DeleteForeverIcon from '@mui/icons-material/DeleteForever' import { Button, IconButton } from '@mui/material' const rows = [ { id: 1, lastName: 'Snow', firstName: 'Jon', age: 35, }, ] const Colors = () => { const navigate = useNavigate() const handleEdit = (row) => { // 这里可以写编辑逻辑,比如跳转到编辑页 navigate(`/edit/${row.id}`) } const handleDelete = (row) => { // 这里可以写删除逻辑,比如弹窗确认后删除 if (window.confirm(`确定要删除${row.firstName} ${row.lastName}吗?`)) { // 执行删除操作 console.log('删除行:', row) } } const columns = [ { field: 'id', headerName: 'ID', width: 70 }, { field: 'firstName', headerName: 'First name', width: 130 }, { field: 'lastName', headerName: 'Last name', width: 130 }, { field: 'age', headerName: 'Age', type: 'number', width: 90, }, { field: 'edit', headerName: 'Edit', width: 150, // 自定义渲染编辑图标按钮 render: (params) => ( <IconButton onClick={() => handleEdit(params.row)} color="primary"> <EditIcon /> </IconButton> ) }, { field: 'delete', headerName: 'Delete', width: 150, // 自定义渲染删除按钮 render: (params) => ( <Button variant="contained" color="error" startIcon={<DeleteForeverIcon />} onClick={() => handleDelete(params.row)} > 删除 </Button> ) }, ] return ( <div style={{ height: 560, width: '100%' }}> <DataGrid sx={{ backgroundColor: 'white' }} rows={rows} columns={columns} pageSize={8} rowsPerPageOptions={[8]} checkboxSelection /> </div> ) } export default Colors
关键说明
render函数接收params参数,params.row可以获取当前行的所有数据,方便在点击事件中使用行ID、姓名等信息。- 用
IconButton包裹图标是Material UI的推荐做法,既能保证样式统一,也自带点击反馈。 - 你可以根据需求调整按钮的样式、图标,或者添加更多逻辑(比如权限判断,只有特定用户能看到编辑按钮)。
内容的提问来源于stack exchange,提问作者Darkpsinight_2
相关产品推荐
相关产品推荐

