【发布时间】:2020-09-30 19:51:16
【问题描述】:
我动态创建表: 在组件表中,我在 json 中设置了表的默认值:
constructor(props) {
super(props);
this.state = {
data: [
{'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': ''}
]
};
}
然后用它来渲染表格:
render() {
return (
<div className={styles}>
<table>
<thead>
<tr>{this.getHeader()}</tr>
</thead>
<tbody>
{this.getRowsData()}
</tbody>
<button onClick={this.addRow}>
Add new row
</button>
</table>
</div>
);
}
这是一个方法实现:
getKeys = function () {
return Object.keys(this.state.data[0]);
};
getHeader = function () {
var keys = this.getKeys();
return keys.map((key, index) => {
return <th key={key}>{key.toLowerCase()}</th>
})
};
getRowsData = function () {
var items = this.state.data;
var keys = this.getKeys();
return items.map((row, index) => {
return <tr key={index}><RenderRow key={index} data={row} keys={keys}/></tr>
})
};
现在我尝试使用这种方法添加新行:
addRow = function () {
let newRows = this.state.data.push({'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': ''});
this.setState({data: newRows});
};
但是当我尝试它时,我收到以下错误:TypeError: Cannot convert undefined or null to object 在
return Object.keys(this.state.data[0]);
确实,在我将新对象推送到“数据”之后,我看到,“数据”不包含任何元素。虽然在此之前它包含 1 个元素:{'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': ''}
【问题讨论】:
标签: reactjs html-table