在React表格中对表行末尾的结果求和,可以通过以下步骤实现:
以下是一个示例代码:
import React, { Component } from 'react';
class Table extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{ id: 1, name: 'John', score: 80 },
{ id: 2, name: 'Jane', score: 90 },
{ id: 3, name: 'Bob', score: 70 },
],
totalScore: 0,
};
}
componentDidMount() {
const { data } = this.state;
const totalScore = data.reduce((sum, row) => sum + row.score, 0);
this.setState({ totalScore });
}
render() {
const { data, totalScore } = this.state;
return (
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{data.map((row) => (
<tr key={row.id}>
<td>{row.id}</td>
<td>{row.name}</td>
<td>{row.score}</td>
</tr>
))}
<tr>
<td colSpan="2">Total Score:</td>
<td>{totalScore}</td>
</tr>
</tbody>
</table>
);
}
}
export default Table;
在上述示例代码中,我们使用了React的状态管理来存储表格数据和求和结果。在组件挂载后,通过reduce方法计算表格数据的求和结果,并将结果存储在state中。然后,在render方法中将求和结果渲染到表格的最后一行单元格中。
请注意,这只是一个简单的示例,你可以根据实际需求进行修改和扩展。对于更复杂的表格操作,你可能需要使用其他库或组件来实现。
领取专属 10元无门槛券
手把手带您无忧上云