javascript - 将对象数组作为表格放置在单元格内:React JS
问题描述
我正在尝试实现一个表,其中我从后端收到的一些数据是一个嵌套的对象数组,我想将它显示在该列的单元格中,就像具有键值对的表一样
const data = [
{
firstName: "Jack",
status: "Submitted",
nested: [
{
name: "test1",
value: "NA"
},
{
name: "test2",
value: "NA"
}
],
age: "14"
}
];
我可以放置从 API 收到的其余字段(嵌套除外)。有人可以帮助如何将这个对象数组放在一个单元格内,就像键值对一样
我正在为这个应用程序使用 react table v6
沙箱:https ://codesandbox.io/s/react-table-row-table-47192
想要输出类似于show more
if items are more than 2 的输出,然后是切换show less
+-----------+-----------+-----+-----------------+
| firstname | status | age | nested |
+-----------+-----------+-----+-----------------+
| Jack | Submitted | 14 | name value |
| | | | ----------- |
| | | | test1 NA |
| | | | |
| | | | test2 NA |
| | | | |
| | | | Show More/Less |
+-----------+-----------+-----+-----------------+
| Simon | Pending | 15 | name value |
| | | | |
| | | | ----------- |
| | | | |
| | | | test3 NA |
| | | | |
| | | | |
| | | | test4 Go |
| | | | |
| | | | Show More/Less |
+-----------+-----------+-----+-----------------+
import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
columns: [],
};
}
componentDidMount() {
this.getData();
this.getColumns();
}
getData = () => {
const data = [
{
firstName: "Jack",
status: "Submitted",
nested: [
{
name: "test1",
value: "NA"
},
{
name: "test2",
value: "NA"
}
],
age: "14"
},
{
firstName: "Simon",
status: "Pending",
nested: [
{
name: "test3",
value: "NA"
},
{
name: "test4",
value: "Go"
}
],
age: "15"
}
];
this.setState({ data });
};
getColumns = () => {
const columns = [
{
Header: "First Name",
accessor: "firstName"
},
{
Header: "Status",
accessor: "status"
},
{
Header: "Age",
accessor: "age"
},
{
Header: "Nested",
id: "nested",
accessor: data => {
let output = [];
data.nested.map(item => {
return output.push(item.value);
});
return output.join(", ");
}
}
];
this.setState({ columns });
};
render() {
return (
<>
<DataGrid
data={this.state.data}
columns={this.state.columns}
/>
</>
);
}
}
解决方案
新编辑:我已根据评论更新了代码沙箱链接
SubComponent
LastEdit:如果你愿意,你可以通过添加道具来改变外观ReactTable
我创建了一个示例沙箱,我在其中添加了
SubComponent
推荐阅读
- javascript - API 的 POST 请求需要找到随机的预先给定包含的字符,从两组字符变成第三组字符
- javascript - 如何使用 Redux 在组件之间共享状态?
- java - jBPM Workbench Docker 之前成功访问后失败
- python - 我的谷歌地图 api 密钥在 python 中不起作用,尽管它可以在 swift 中运行
- python - 是否可以测试 DBSCAN 聚类算法?如果是,如何?
- python - How to assign a tf.placeholder?
- amazon-dynamodb - 如何在 DynamoDB 中设置字符串字段的最大长度?
- java - 堆栈跟踪循环
- python - Wagtail ModelAdmin:不隐藏小部件标签
- mysql - 如何从特定数据 order_by