You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Material-UI Data-Grid表格中正确渲染显示图片

问题原因

Material UI DataGrid 默认只会将字段对应的原始值以纯文本形式渲染,你没有为image列配置自定义内容渲染规则,因此只会展示图片URL文本,不会自动渲染为图片元素。

解决方案

在image列的配置中添加renderCell属性,自定义该列的渲染逻辑,返回<img>标签加载对应URL的图片即可。

修改后的完整代码

import { DataGrid } from '@material-ui/data-grid';

const columns = [
  {
    field: 'image',
    headerName: 'Image',
    width: 150,
    editable: true,
    // 新增自定义渲染逻辑
    renderCell: (params) => (
      <img 
        src={params.value} 
        alt={params.row.name} 
        style={{ width: '100%', height: 'auto', maxHeight: 120, objectFit: 'contain' }} 
      />
    )
  },
  {
    field: 'name',
    headerName: 'Name',
    width: 150,
    editable: true,
  },
];

const rows = [
  {
    id: 1,
    image: "替换为实际的图片URL",
    type: 'image',
    name: 'Cheese Burger',
    price: 10_000,
    menu: 'Daily Menu',
    category: 'Burgers'
  },
  {
    id: 2,
    image: "替换为实际的图片URL",
    name: 'Diet Coke',
    price: 10_000,
    menu: 'Daily Menu',
    category: 'Drinks'
  },
];

export const ItemsTable = () => {
  return (
    <div style={{ height: 300, width: '100%' }} className="mt-7">
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={5}
        checkboxSelection
        disableSelectionOnClick
      />
    </div>
  );
}

补充说明

  • 你可以自行调整<img>标签的样式属性,控制图片的尺寸、裁剪方式等适配你的页面需求。
  • 如果你需要支持image列的编辑功能,还需要额外配置renderEditCell属性自定义编辑态的组件,实现图片URL修改的交互逻辑。
  • 如果你使用的是MUI v5版本,只需要将导入语句替换为import { DataGrid } from '@mui/x-data-grid';即可,列配置的逻辑完全兼容。

内容的提问来源于stack exchange,提问作者Mo1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:51:03