レコードが表に示されているReactJSで簡単なコードを記述しました。各行の名前は表示されますが、レコード/行の指定と給与はその行をクリックすると表示されます。問題は、詳細(名前、指定、&給与)を入力して新しいレコードを追加すると、入力された詳細でレコードの代わりに空白のレコードが追加されることです。何が問題なのか教えてください。ReactJSに入力された詳細の行の代わりに空レコード/行が追加されました
コード:
var RecordsComponent = React.createClass({
getInitialState: function() {
return {
records: [{name:'Kevin Petersen',designation:"Junior Software Engineer",salary:"$1000"}, {name:'Michel Johnson',designation:"Senior Software Engineer",salary:"$2500"},{name:'Shane Bond',designation:"HR Manager",salary:"$1250"}],
newRecord: [{name:'new name', designation:'new designation', salary:'new salary'}],
expandedRecords : []
}
},
render : function() {
return (
<div className="container" style={{"width" : "50%", "alignment" : "center"}}>
<table className="table table-striped">
<thead>
<tr>
<th colSpan={2}>Records</th>
</tr>
</thead>
<tbody>
{this.state.records.map((r) => (
<tr>
<td onClick={this.showDetails}>
{r.name}
{this.renderDesignation(r.name)}<span></span>
{this.renderSalary(r.name)}
</td>
<td>
<button className="tableBtn" onClick={() => this.deleteRow(r)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
<input type="text" id={"newNameId"} placeholder={"name"} onChange={this.updateNewName}></input>
<input type="text" id={"newDesId"} placeholder={"designation"} onChange={this.updateNewDesignation}></input>
<input type="text" id={"newSalId"} placeholder={"salary"} onChange={this.updateNewSalary}></input>
<button id="addBtn" onClick={this.addRow}>ADD</button>
</div>
);
},
updateNewName: function(component) {
this.setState({
newRecord: {name:component.target.value},
});
},
updateNewDesignation: function(component) {
this.setState({
newRecord: {designation:component.target.value},
});
},
updateNewSalary: function(component) {
this.setState({
newRecord: {salary:component.target.value}
});
},
addRow : function() {
var records = this.state.records;
var newRecord = this.state.newRecord;
records.push(newRecord)
this.setState({records: records})
},
deleteRow : function(record) {
this.setState({
records: this.state.records.filter(r => r !== record)
});
},
showDetails : function(record) {
let expandedRecords = this.state.expandedRecords;
expandedRecords.push(record.target.innerHTML);
this.setState({...this.state, expandedRecords: expandedRecords });
},
renderDesignation : function(name){
if(this.state.expandedRecords.includes(name)) {
var row = this.state.records.filter(r=> r.name === name)[0]
return(<td>{"Designation: "+row.designation}</td>);
}
return;
},
renderSalary : function(name){
if(this.state.expandedRecords.includes(name)) {
var row = this.state.records.filter(r=> r.name === name)[0]
return(<td>Salary: {row.salary}</td>);
}
return;
}
});
React.render(
<RecordsComponent />,
document.getElementById('display')
);
「状態」を変更しないでください。例えば 'addRow'では' this.setState({records:[... this.state.records、newRecord]}) 'を使います。また、配列を通してマッピングしていて、 'key'を' tr'要素に割り当てていません。 – mersocarlin
'createClass'は廃止され、Reactの次のバージョンでは全くサポートされません。 – Chris