React-Data-Grid行首单元格名称显示及单元格访问方法问询
React-Data-Grid 问题解答:显示化合物名称与访问单元格数据
1. 解决首列化合物名称不显示的问题
问题根源是列配置的key与行数据的字段不匹配:
你的首列key设为Compound,但行数据里存储化合物名称的字段是title或name(部分行只有title),React-Data-Grid无法自动匹配到对应值。
修复方案(二选一即可)
方案1:统一行数据字段 + 匹配列key
把所有行的化合物名称统一存到同一个字段(比如compound),然后修改列配置的key为compound:
// 修改rows数组,统一字段 const rows = [ { id: 0, compound: 'Triple-20', ... }, { id: 1, compound: 'Urea', ... }, { id: 2, compound: 'Ammonium Sulfate', ... }, // 其他行同理更新字段名 ]; // 修改首列配置 const columns = [ { key: 'compound', name: 'COMPOUND' }, // 其他列保持不变 ];
方案2:使用formatter兼容现有字段
如果不想修改行数据结构,给首列添加formatter函数,指定要显示的内容:
const columns = [ { key: 'Compound', name: 'COMPOUND', formatter: (row) => row.title || row.name // 优先取title,没有则取name }, // 其他列保持不变 ];
2. 访问单元格数据实现计算与汇总
React-Data-Grid通过状态管理和事件监听处理单元格数据,核心是把rows放到组件状态中,通过修改状态实现数据更新与计算。
步骤1:用useState管理行数据
把静态rows改成组件状态,方便后续修改:
import { useState } from 'react'; import DataGrid from 'react-data-grid'; import './App.css'; // 定义贴合业务的Row类型 export interface Row { id: number; title: string; name?: string; 'ENTER GRAMS'?: number; N?: number; P?: number; K?: number; Mg?: number; Ca?: number; S?: number; Fe?: number; Mn?: number; Zn?: number; Bo?: number; Cu?: number; Cl?: number; Na?: number; Mo?: number; SILICA?: number; } function App() { // 初始化行数据到状态 const [rows, setRows] = useState<Row[]>([ { id: 0, title: 'Triple-20', name: 'Triple-20' }, { id: 1, title: 'Urea', name: 'Urea' }, // 其他行数据保持不变 ]); const rowKeyGetter = (row: Row) => row.id; // 后续添加事件处理函数... }
步骤2:监听单元格变化,实现实时计算
添加onCellChange事件,当用户修改单元格(比如输入克数)时,触发ppm计算:
// 示例:根据化合物类型和输入的克数计算养分ppm值(需补充其他化合物的养分比例) const calculateNutrientPPM = (row: Row, grams: number) => { // 预设各化合物的养分比例(百分比) const nutrientMap: Record<string, Record<string, number>> = { 'Triple-20': { N: 20, P: 20, K: 20 }, 'Urea': { N: 46 }, 'Ammonium Sulfate': { N: 21, S: 24 }, // 其他化合物的养分比例需根据实际数据补充 }; const ratios = nutrientMap[row.title] || {}; // 换算ppm的系数(根据你的业务逻辑调整,比如溶液体积等) const ppmConversionFactor = 10; return Object.entries(ratios).reduce((acc, [key, ratio]) => { acc[key as keyof Row] = (grams * ratio / 100) * ppmConversionFactor; return acc; }, {} as Partial<Row>); }; // 单元格变化事件处理 const handleCellChange = (rowIdx: number, columnKey: string, newValue: any) => { const updatedRows = [...rows]; const targetRow = { ...updatedRows[rowIdx] }; // 更新当前单元格的值 targetRow[columnKey as keyof Row] = newValue; // 如果修改的是"ENTER GRAMS"列,自动计算ppm值 if (columnKey === 'ENTER GRAMS') { const ppmValues = calculateNutrientPPM(targetRow, newValue); Object.assign(targetRow, ppmValues); } updatedRows[rowIdx] = targetRow; setRows(updatedRows); };
在DataGrid组件中添加事件监听:
return ( <DataGrid columns={columns} rows={rows} rowKeyGetter={rowKeyGetter} style={{ height: 810 }} onCellChange={handleCellChange} /> );
步骤3:实现数据汇总
遍历状态中的rows数组,累加各养分的ppm值:
// 计算所有化合物的养分总和 const getTotalNutrients = () => { return rows.reduce((total, row) => { return { N: total.N + (row.N || 0), P: total.P + (row.P || 0), K: total.K + (row.K || 0), Mg: total.Mg + (row.Mg || 0), Ca: total.Ca + (row.Ca || 0), S: total.S + (row.S || 0), Fe: total.Fe + (row.Fe || 0), Mn: total.Mn + (row.Mn || 0), Zn: total.Zn + (row.Zn || 0), Bo: total.Bo + (row.Bo || 0), Cu: total.Cu + (row.Cu || 0), Cl: total.Cl + (row.Cl || 0), Na: total.Na + (row.Na || 0), Mo: total.Mo + (row.Mo || 0), SILICA: total.SILICA + (row.SILICA || 0), }; }, { N: 0, P: 0, K: 0, Mg: 0, Ca: 0, S: 0, Fe: 0, Mn: 0, Zn: 0, Bo: 0, Cu: 0, Cl: 0, Na: 0, Mo: 0, SILICA: 0 }); }; // 在组件中渲染汇总结果 const totalNutrients = getTotalNutrients(); return ( <div> <DataGrid columns={columns} rows={rows} rowKeyGetter={rowKeyGetter} style={{ height: 810 }} onCellChange={handleCellChange} /> <div style={{ padding: '10px', backgroundColor: '#f5f5f5' }}> <h3>养分汇总</h3> <p>N: {totalNutrients.N.toFixed(2)} ppm</p> <p>P: {totalNutrients.P.toFixed(2)} ppm</p> <p>K: {totalNutrients.K.toFixed(2)} ppm</p> {/* 其他养分的汇总展示可按需添加 */} </div> </div> );
内容的提问来源于stack exchange,提问作者learnedToCode
相关产品推荐
相关产品推荐

