我正在开发一个使用this.state.data.map()来自动生成带有添加组件输入内容的表的应用程序。生成的输入会根据在应用程序中选择的选项卡而变化。我想找到在任何时间点生成的每个输入的数量值的总和。任何帮助将不胜感激:)
render() {
return (
<div>
<a href="/login">
<button>Log Out</button>
</a>
<Tabs activeKey={this.state.activeTab} onSelect={this.handleSelect}>
<Tab eventKey={2018} title={<YearTabsRouter year="2018" />}>
<MonthTabs
year="2018"
monthlyActiveTab={this.state.selectedMonth}
/>
</Tab>
<Tab eventKey={2019} title={<YearTabsRouter year="2019" />}>
<MonthTabs
year="2019"
monthlyActiveTab={this.state.selectedMonth}
/>
</Tab>
<Tab eventKey={2020} title={<YearTabsRouter year="2020" />}>
<MonthTabs
year="2020"
monthlyActiveTab={this.state.selectedMonth}
/>
</Tab>
<Tab eventKey={2021} title={<YearTabsRouter year="2021" />}>
<MonthTabs
year="2021"
monthlyActiveTab={this.state.selectedMonth}
/>
</Tab>
<Tab eventKey={2022} title={<YearTabsRouter year="2022" />}>
<MonthTabs
year="2022"
monthlyActiveTab={this.state.selectedMonth}
/>
</Tab>
</Tabs>
<Add
selectedMonth={this.state.selectedMonth}
selectedYear={this.state.selectedYear}
/>
<table>
<thead>
<tr>
<th />
<th className="desc-col">Description</th>
<th className="button-col">Amount</th>
<th className="button-col">Month</th>
<th className="button-col">Year</th>
<th className="button-col">Update</th>
<th className="button-col">Delete</th>
</tr>
</thead>
<tbody>
{this.state.data.map(exp => {
return (
<tr>
<td className="counterCell" />
<td className="desc-col">{exp.description}</td>
<td className="button-col" id="amt" refs={this.amount}>
{exp.amount}
</td>
<td className="button-col">{exp.month}</td>
<td className="button-col">{exp.year}</td>
<td className="button-col">
<Update expense={exp} />
</td>
<td className="button-col">
<Delete expense={exp} />
</td>
</tr>
);
})}
<th>
Total: <span id="demo">{getTotal()}</span>
</th>
</tbody>
</table>
</div>
);
}
答案 0 :(得分:0)
在渲染之前在渲染器中执行.map,以计算总值并将其分配给渲染器中的局部变量,例如
render(){
const { data } = this.state;
let totalPrice = 0;
const items = data && data.map(exp => {
totalPrice += exp.amount;
return (
<tr>
<td className="counterCell" />
<td className="desc-col">{exp.description}</td>
<td className="button-col" id="amt" refs={this.amount}>
{exp.amount}
</td>
<td className="button-col">{exp.month}</td>
<td className="button-col">{exp.year}</td>
<td className="button-col">
<Update expense={exp} />
</td>
<td className="button-col">
<Delete expense={exp} />
</td>
</tr>
)
})
return(
<div>
<table>
<thead>
<tr>
<th />
<th className="desc-col">Description</th>
<th className="button-col">Amount</th>
<th className="button-col">Month</th>
<th className="button-col">Year</th>
<th className="button-col">Update</th>
<th className="button-col">Delete</th>
</tr>
</thead>
<tbody>
{items}
<tr>
<th>
Total: <span id="demo">{totalPrice}</span>
</th>
</tr>
</tbody>
</table>
</div>
)
}