如何为动态输入对象数组编写handleChange函数适配MERN栈发票生成器
实现动态输入保存的方案
你完全不需要修改已经写好的className和CSS绑定,只需要调整onChange的传参逻辑,新增handleChange函数即可:
1. 调整渲染代码的onChange绑定
仅需给每个输入框的onChange传入当前行索引和对应存储字段名,同时建议修改重复的固定id为带索引的格式,避免多行列时出现DOM id冲突:
itemValues.map((item, i) => { const descId = `description-${i}`; const rateId = `rate-${i}`; const quanId = `quantity-${i}`; const amonId = `amount-${i}`; const taxId = `tax-${i}`; return( <div key={i} className="item-row"> <input className="item item-description" type="text" id={descId} name={descId} placeholder="Item description" data-id={descId} onChange={(e) => this.handleChange(e, i, 'description')} /> <input className="item item-rate" type="text" id={rateId} name={rateId} placeholder="Item rate" data-id={rateId} onChange={(e) => this.handleChange(e, i, 'rate')} /> <input className="item item-quantity" id={`item-quantity-${i}`} type="text" placeholder="item quantity" data-id={quanId} onChange={(e) => this.handleChange(e, i, 'quantity')} /> <input className="item item-amount" id={`item-amount-${i}`} type="text" placeholder="item amount" data-id={amonId} onChange={(e) => this.handleChange(e, i, 'amount')} /> {this.state.taxation === "None" ? "" : <input className="item item-tax" id={`item-tax-${i}`} type="text" placeholder="tax(%)" data-id={taxId} onChange={(e) => this.handleChange(e, i, 'tax')} /> } <input type='button' value='remove' onClick={() => this.removeClick(i)} /> </div> ) })
2. 编写handleChange处理函数
通过浅拷贝state数组修改对应位置的字段值,避免直接修改原state:
handleChange = (e, rowIndex, field) => { // 浅拷贝itemValues数组,遵循state不可变原则 const newItemValues = [...this.state.itemValues]; // 更新对应行对应字段的输入值 newItemValues[rowIndex][field] = e.target.value; // 可选:自动计算金额(单价*数量),不需要可以删掉这段 if (field === 'rate' || field === 'quantity') { const rate = Number(newItemValues[rowIndex].rate) || 0; const quantity = Number(newItemValues[rowIndex].quantity) || 0; newItemValues[rowIndex].amount = (rate * quantity).toFixed(2); } // 触发state更新 this.setState({ itemValues: newItemValues }); }
3. 可选:删除行功能实现
如果还没写remove按钮的逻辑,可以参考:
removeClick = (rowIndex) => { // 过滤掉要删除的行 const newItemValues = this.state.itemValues.filter((_, idx) => idx !== rowIndex); this.setState({ itemValues: newItemValues }); }
内容的提问来源于stack exchange,提问作者MichaelKwanzaa
相关产品推荐
相关产品推荐

