如何在React中将多个表单输入结果添加到数组状态 [英] How to add multiple form input results into array State in React

查看:107
本文介绍了如何在React中将多个表单输入结果添加到数组状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新手,我通过构建一个小型应用程序来计算React的现金(我的孩子可以使用的应用程序)来尝试学习React.我正在动态创建5个组件,每个组件都有一个输入字段.这些输入字段接受一个条目(一个数字),并将该输入乘以我要从对象映射的固定金额(5个组成部分中的每个固定金额($ 20,$ 10,$ 5,$ 2和$ 1固定金额)).这部分效果很好.$ 10 x 2显示$ 20.

I'm am an all around new coder and trying to learn React by building a small app that calculates how much cash one has (an app my kids can use). I am dynamically creating 5 components, each with an input field. Those input fields accepts an entry (a number) and multiplies that input by the fixed amount that I am mapping out from an object ($20, $10, $5, $2 and $1 fixed amounts) for each of the 5 components. That part works great. $10 x 2 is showing me $20.

但是,要在键入时将所有5个帐单金额总计加起来,我想我需要将它们放入一个数组中,然后获取该数组的总和以显示最终总计.事情没有进行,上周我一直在寻找一种方法来编码我的 onChange 处理程序.我只是被困住了.任何帮助将不胜感激.对于任何难以阅读的代码,我深感抱歉.

However, to add up all 5 of the bill amount totals as they are keyed in, I was thinking I need to put them into an array and then get the sum of the array to show the final total. Things aren't working and I've been searching this past week for a way to code my onChange handler. I'm just flat out stuck. Any help would be so greatly appreciated. I am very sorry for any hard to read code.

这是 jsfiddle (请原谅缺乏样式的人)

Here's the jsfiddle (please excuse the lack of styling)

推荐答案

我可以通过打开JavaScript控制台(F12或右键单击->检查)轻松找到错误.

I was able to find the error easily by opening the javascript console (F12 or right click -> inspect).

抛出错误是因为您确实将handleCashInput作为道具传递给CashItemsList

The error was thrown because you did pass handleCashInput as a prop to CashItemsList

< CashItemsList键= {bill.id} bill = {bill} onChange = {this.handleCashInput}/>

使用带有reduce的数组也不是一个好主意,因为如果删除一个金额然后重新输入,则总数将是错误的.我做了以下的事情来解决它:

Also using an array with reduce was not a good idea because if you delete an amount and re-enter it, the total will be wrong. I did the following to solve it:

  1. 我使用对象而不是数组
    {1:0,2:0,3:0,4:0,5:0}

我将帐单ID传递给handleCashInput以便能够更改金额 this.props.onChange(this.props.bill.id,newBillSubTotal)

I pass the bill id to handleCashInput to be able to change the amount this.props.onChange(this.props.bill.id, newBillSubTotal)

这是我的 JSFiddle

这篇关于如何在React中将多个表单输入结果添加到数组状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆