如何编辑React-bootstrap表格单元格内的数组?编辑时显示[object Object]怎么解决
问题原因
你当前使用的react-bootstrap-table2-editor单元格编辑模块,默认会直接读取dataField绑定的原始值转为字符串作为编辑框默认内容。你所有涉及代表信息的列绑定的都是完整的representants对象数组,编辑时数组转字符串就会出现[object Object],你平时正常展示是依赖自定义的formatter提取数组内对应字段渲染,但编辑模块不会复用formatter的输出结果。
解决步骤
1. 调整数据映射逻辑
不要把完整的对象数组绑定给业务字段,提前把需要展示、编辑的内容从数组中提取为可直接识别的字符串,同时保留原始数组供后续更新回写:
const data = societes && societes.map((societe) => ({ societe: societe.nomSociete, nationalite: societe.nationalite, // 多个代表用换行拼接,单个代表直接取第一个元素即可 identite: societe.representants.map(x => x.identite).join('\n'), nationaliteRepresentant: societe.representants.map(x => x.nationaliteRepresentant).join('\n'), pieceIdentite: societe.representants.map(x => x.pieceIdentite).join('\n'), dateDebut: societe.representants.map(x => x.dateDebut).join('\n'), dateFin: societe.representants.map(x => x.dateFin).join('\n'), // 保留原始代表数组用于更新 rawRepresentants: societe.representants }));
对应调整你的formatter函数,拆分字符串渲染即可,不用再操作对象数组:
const representantsIdentite = (cell) => { return cell.split('\n').map((content, idx) => ( <p key={idx}> <span>{content}</span> </p> )); }; // 其他几个代表信息的formatter同理修改即可
2. 给对应列配置编辑属性
修改列配置,指定编辑控件类型、取值和赋值逻辑,编辑后自动同步到原始数组:
// 以identite列为例,其他代表信息列同理修改 { dataField: 'identite', text: 'Test3', formatter: representantsIdentite, headerStyle: { backgroundColor: '#e9ecef', }, // 新增编辑器配置 editor: { // 多值用文本域更适合 type: 'textarea', // 编辑框默认值直接取我们预处理好的字符串 getValue: (column, row) => row[column.dataField], // 保存后更新原始数组 setValue: (row, column, inputValue) => { const inputValues = inputValue.split('\n').filter(item => item.trim()); const updatedRepresentants = row.rawRepresentants.map((rep, index) => ({ ...rep, [column.dataField]: inputValues[index] ?? rep[column.dataField] })); return { ...row, [column.dataField]: inputValue, rawRepresentants: updatedRepresentants } } } }
3. 移除无效代码
你当前写的onStartEdit方法里的row.identite.map((x) => 123)没有赋值操作也没有返回值,完全不生效,可以直接删除。
内容的提问来源于stack exchange,提问作者Ilias SANATI
相关产品推荐
相关产品推荐

