我有 3 个标签可以在单击按钮时接收输入,然后我需要来自第三个输入值的总和,代码有点工作,但不是得到第三个输入的总和,而是看起来像下面的图像,其中输入组合有点像一个字符串(不知道如何调用它)。感谢任何帮助 Total 的样子
这是我的完整代码
import React, { Component } from 'react';
import './Bootstrap/css/bootstrap.min.css';
class App extends Component {
constructor(){
super();
this.state = {
mahasiswa : [],
tgl : null,
nama : null,
nilai : null,
nilaiArray: []
}
}
setValueState(event){
var value = event.target.value
this.setState({
[event.target.name] : value
})
var nilaiArrayTmp = this.state.nilaiArray;
nilaiArrayTmp.push(value?parseFloat(value).toFixed(2):0)
this.setState({
nilaiArray: nilaiArrayTmp
})
}
addData(){
var data_tmp = this.state.mahasiswa;
data_tmp.push({nim : this.state.tgl, nama : this.state.nama, nilai : this.state.nilai});
this.setState({
mahasiswa : data_tmp
})
}
render() {
const total=(this.state.mahasiswa.reduce((total,{nilai}) => total = total + nilai , 0 ));
return (
<div className="container">
<h2><b>Daftar Pengeluaran</b></h2>
<div className="form-container">
<div className="form-group">
<label>Waktu:</label>
<input type="text" name="tgl" value={this.state.tgl} onChange={this.setValueState.bind(this)} className="form-control" />
</div>
<div className="form-group">
<label>Deskripsi:</label>
<input type="text" name="nama" value={this.state.nama} onChange={this.setValueState.bind(this)} className="form-control" />
</div>
<div className="form-group">
<label>Jumlah:</label>
<input type="number" name="nilai" value={this.state.nilai} onChange={this.setValueState.bind(this)} className="form-control" />
</div>
<br />
<button onClick={this.addData.bind(this)} type="button" className="btn btn-primary">Tambah</button>
</div>
<br />
<table className="table">
<thead>
<tr>
<th>No.</th>
<th>Waktu</th>
<th>Deskripsi</th>
<th>Jumlah</th>
</tr>
</thead>
<tbody>
{this.state.mahasiswa.map((mhs, index)=>(
<tr key={index}>
<td>{index+1}</td>
<td>{mhs.tgl}</td>
<td>{mhs.nama}</td>
<td>{mhs.nilai}</td>
</tr>
))}
<tr>
<td></td>
<td></td>
<td>Total:</td>
<td>{total}</td>
</tr>
</tbody>
</table>
</div>
);
}
};
export default App;