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

MUI X DataGrid v7中Cell插槽组件如何访问value等字段

MUI X DataGrid v7 自定义Cell组件访问值的正确方式

在v7版本中,DataGrid的cell插槽props结构做了重构,原来直接挂载在GridCellProps上的value、formattedValue和children属性不再直接暴露,需要通过以下方式获取:

获取原始值

可以通过DataGrid提供的API方法getCellValue获取单元格的原始值,或者直接从行数据中读取:

// 方式1:通过API(推荐,会自动处理valueGetter等列配置)
const value = props.api.getCellValue(props.id, props.field);

// 方式2:直接从行数据读取(适合简单场景)
const value = props.row[props.field];

获取格式化后的值

使用API方法getCellFormattedValue获取经过列配置(如valueFormatter)处理后的格式化值:

const formattedValue = props.api.getCellFormattedValue(props.id, props.field);

获取默认单元格内容(替代原children)

如果需要保留DataGrid默认的单元格渲染结果(对应v6中的children),可以调用renderDefaultCell()方法:

const defaultCellContent = props.renderDefaultCell();

完整示例

const CustomCell = (props: GridCellProps) => {
  const value = props.api.getCellValue(props.id, props.field);
  const formattedValue = props.api.getCellFormattedValue(props.id, props.field);
  const defaultContent = props.renderDefaultCell();

  return (
    <div style={{ padding: '8px' }}>
      <span>原始值: {value}</span>
      <span style={{ marginLeft: '16px' }}>格式化值: {formattedValue}</span>
      <div style={{ marginTop: '4px', color: '#666' }}>默认渲染: {defaultContent}</div>
    </div>
  );
};

// 使用方式不变
<DataGrid slots={{ cell: CustomCell }} {...otherProps} />

注意事项

  • props.api是DataGrid上下文自动注入的,确保自定义组件在DataGrid内部使用时可以正常访问
  • 优先使用API方法获取值,因为它们会自动处理列的valueGetter、valueFormatter等配置,比直接读取行数据更可靠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:02:34