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
相关产品推荐
相关产品推荐

