MUI X Data Grid货币字符串聚合拼接而非求和的修复方法
解决MUI X Data Grid中带$符号的价格字段聚合求和问题
要解决带$符号的字符串价格字段聚合时出现字符串拼接的问题,你需要自定义聚合函数提取数值计算,同时通过值格式化器保持前端显示带$的格式,具体实现如下:
1. 自定义价格求和聚合函数
创建聚合函数,提取字符串中的数字部分转换为数值后求和:
const customPriceSum = (params) => { return params.children .reduce((acc, row) => { // 移除$符号并转换为数字,处理异常值 const price = parseFloat(row.UnitPrice.replace(/\$/g, '')); return acc + (isNaN(price) ? 0 : price); }, 0); };
2. 配置列的聚合规则与显示格式
在UnitPrice列的定义中,绑定自定义聚合函数,并添加valueFormatter统一渲染带$的格式:
const columns = [ { field: "UnitsNeeded", headerName: "QTY", type: "number" }, { field: "UnitPrice", headerName: "Price", type: "number", // 指定自定义聚合函数 aggregation: { function: customPriceSum }, // 格式化显示带$的价格 valueFormatter: (params) => { const value = params.value; // 区分原始行数据(字符串)和聚合结果(数字)的显示逻辑 return typeof value === 'number' ? `$${value}` : value; } } ];
完整代码示例
import * as React from "react"; import { DataGridPremium } from "@mui/x-data-grid-premium"; const rows = [ { ProductCategoryName: "", ProductName: "Magnum Brownie 80ml", UnitPrice: '$2160', UnitsNeeded: 1, hierarchy: ["cat1", "Magnum Brownie 80ml"] }, { ProductCategoryName: "", ProductName: "Magnum Brownie 80ml", UnitPrice: '$2160', UnitsNeeded: 1, hierarchy: ["cat2", "Magnum Brownie 80ml"] }, { ProductCategoryName: "", ProductName: "Magnum Brownie", UnitPrice: '$2160', UnitsNeeded: 1, hierarchy: ["cat2", "Magnum Brownie"] } ]; // 自定义价格求和聚合函数 const customPriceSum = (params) => { return params.children .reduce((acc, row) => { const price = parseFloat(row.UnitPrice.replace(/\$/g, '')); return acc + (isNaN(price) ? 0 : price); }, 0); }; const columns = [ { field: "UnitsNeeded", headerName: "QTY", type: "number" }, { field: "UnitPrice", headerName: "Price", type: "number", aggregation: { function: customPriceSum }, valueFormatter: (params) => { const value = params.value; return typeof value === 'number' ? `$${value}` : value; } } ]; const getTreeDataPath = (row) => row.hierarchy; const getRowId = (row) => row.hierarchy.join("/"); export default function AggregationTreeData() { return ( <div style={{ height: 450, width: "100%" }}> <DataGridPremium treeData rows={rows} columns={columns} getTreeDataPath={getTreeDataPath} getRowId={getRowId} groupingColDef={{ headerName: "Product Name", width: 250 }} initialState={{ aggregation: { model: { UnitsNeeded: "sum", UnitPrice: "sum" } } }} /> </div> ); }
说明
- 自定义聚合函数
customPriceSum遍历分组下的所有子行,提取价格字符串中的有效数值并累加,避免字符串拼接问题。 valueFormatter统一处理原始行数据和聚合结果的显示格式,确保前端展示的价格都带有$符号。
内容的提问来源于stack exchange,提问作者Jidonu2
相关产品推荐
相关产品推荐

