[英]Render multiple inputs React
I've created a simple Budget app using React . 我使用React创建了一个简单的预算应用程序 。 The user can add Income/Expense Description and Value by filling out the inputs and the final result gets added to the Expenses/Incomes lists.
用户可以通过填写输入来添加收入/费用描述和值,并将最终结果添加到费用/收入列表中。
I managed to add the Income/Expenses values (numbers): I've created a setState with incomes: [1, 3, 4], map around the income array and print out the values by updating the state. 我设法添加收入/支出值(数字):我创建了一个收入为:[1,3,4]的setState,围绕收入数组进行映射,并通过更新状态打印出值。
I can't understand how to add the description. 我无法理解如何添加说明。 I've checked some questions here on Stack but they only use setState and creating a state for each element (incomes, incomeValues, expenses, expensesValue), which is not what I want.
我在Stack上检查过一些问题,但是他们只使用setState并为每个元素创建一个状态(incomes,incomeValues,expenses,expensesValue),这不是我想要的。
Is there a way to do this without involving too many states? 有没有办法在不涉及太多国家的情况下做到这一点? Maybe using an Object?
也许使用对象?
Your state is an object 你的国家是一个对象
{
monthlyBudget: 0,
incomesSum: 0,
expensesSum: 0,
incomes: [0],
expenses: [0]
}
What you could do instead of adding more numbers to the incomes array is add objects to the incomes array. 您可以做什么而不是向incomes数组添加更多数字是将对象添加到incomes数组。 Exactly like you guessed.
完全像你猜的那样。
{
monthlyBudget: 0,
incomesSum: 0,
expensesSum: 0,
incomes: [
{ amount: 0, description: 'some description' },
{ amount: 1, description: 'second description' },
]
expenses: [0]
}
in which case you would still use map to access the properties of the object. 在这种情况下,您仍然可以使用map来访问对象的属性。
this.sate.incomes.map(income => {
// do something with income.amount
// do something with income.description
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.