我正在研究如何在React.js中创建表。 我有一个简单的代码,需要像这样的列表(硬编码):
data = [{
"item1": 0.0,
"item1": 0.0,
"item1": 0,
"item1": 0.36363636363636365,
"item1": "string",
"item1": 0,
"item1": "string",
"item1": "string",
"item1": 0.0,
"item1": 0.2569125,
"item1": 0.0625,
"item1": 0.0521760194628226,
"item1": 2,
"item1": 0.0534268,
"item1": 0.0,
"item1": 1180.0,
"item1": 0.0
}];
并在render()中创建一个DataTable对象:
render() {
return (
<div>
<DataTable data = {data}/>
</div>
);
}
该类只需执行以下操作:
class DataTable extends Component {
createColumnsArray() {
var columns = [];
for (var i in this.props.data) {
var keysArr = Object.keys(this.props.data[i]);
for (var index in keysArr) {
var element = {};
element.dataField = keysArr[index];
element.text = keysArr[index];
columns.push(element);
}
}
return columns;
}
render() {
var columns = this.createColumnsArray();
return (
<div className="Tables">
<p className="Table-header">Country Statistics</p>
<BootstrapTable keyField='id' data={ this.props.data } columns={ columns } />
</div>
);
}
}
export default DataTable
顺便说一下,Chrome控制台上会显示以下警告:
index.js:2178 Warning: Each child in an array or iterator should have a unique "key" prop. See link for more information.
in tbody (created by Body)
in Body (created by BootstrapTable)
in table (created by BootstrapTable)
in div (created by BootstrapTable)
in BootstrapTable
in DataProvider (created by BootstrapTableContainer)
in BootstrapTableContainer (at DataTable.js:27)
in div (at DataTable.js:25)
in DataTable (at App.js:43)
in div (at App.js:39)
in App (at index.js:9)
我真的不明白如何消除此警告。
答案 0 :(得分:0)
编辑:您需要在数据数组中具有id属性,因为您是在id
道具中引用此keyField
的。
您的数据数组应遵循以下结构:
data = [{
"id": 1,
"item1": 0.0,
"item1": 0.0,
"item1": 0,
...
}, {
"id": 2,
"item2": 0.36363636363636365,
"item2": "string",
"item2": 0,
"item2": "string",
...
}...];
编辑:也只需在发现的组件调用keyField
中更改<BootstrapTable keyField='item1' data={ this.props.data } columns={ columns } />
。
答案 1 :(得分:0)
因此,确保关键字段的名称与数据字段中的名称匹配。通过删除和/或转换 null 来清理数据。