[英]how to add row with table column summation in react js
我使用 react js 創建數據表。這是我當前的代碼 output。
但我需要顯示Net Lost和Net Returned列 Summation 。
就像下面的視覺效果。
如您所見,在底部有一行,它顯示了“Net Lost”和“Net Returned”的總和。
當前代碼:
import { useState } from "react";
import "./style.css";
export default function DataTable4() {
const rawData = [
[7, '', 2, 1, 4, 3],
[8, 3, '', 5, 3],
['', '', '', ''],
[4, 4, '']
];
return (
<table>
<thead>
<tr>
<th>Week</th>
<th>1 </th>
<th>2 </th>
<th>3 </th>
<th>4 </th>
<th>Net Lost</th>
<th>Net Returned</th>
</tr>
</thead>
<tbody>
{rawData.map((item, index) => {
return (
<tr>
<th>{index + 1}</th>
{[...Array(6 - item.length)].map((item) => {
return <td></td>; //for empty values
})}
{item.map((itm) => {
return <td>{itm}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
}
我試圖添加另一個<tr>
標記來執行此操作,但它會引發錯誤。
我們可以使用初始rawData
添加新的兩個 arrays 。 然后得到NetLost
和Net Returned
的總和。
import { useState } from "react";
import "./style.css";
export default function DataTable4() {
const rawData = [
[7, '', 2, 1, 4, 3],
[8, 3, '', 5, 3],
['', '', '', ''],
[4, 4, '']
];
const NetLostInitial= rawData.map(x => x[x.length-2]);
const NetReturnedInitial= rawData.map(x => x[x.length-1]);
const NetLost = NetLostInitial.filter(
element => typeof element === 'number'
);
const NetReturned = NetReturnedInitial.filter(
element => typeof element === 'number'
);
const TotalNetLost=NetLost.reduce((partialSum, a) => partialSum + a, 0);
const TotalNetReturned=NetReturned.reduce((partialSum, a) => partialSum + a, 0);
return (
<table>
<thead>
<tr>
<th>Week</th>
<th>1 </th>
<th>2 </th>
<th>3 </th>
<th>4 </th>
<th>Net Lost</th>
<th>Net Returned</th>
</tr>
</thead>
<tbody>
{rawData.map((item, index) => {
return (
<>
<tr>
<th>{index + 1}</th>
{[...Array(6 - item.length)].map((item) => {
return <td></td>; //for empty values
})}
{item.map((itm) => {
return <td>{itm}</td>;
})}
</tr>
</>
);
})}
<tr>
<th></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{TotalNetLost}</td>
<td>{TotalNetReturned}</td>
</tr>
</tbody>
</table>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.