完全动态地从 JSON 创建一个表 [英] Create a table from JSON completely dynamically
问题描述
我想从包含动态 th
的 JSON 数组创建整个表,因此将头部部分解耦为:
从'react'导入React;从'./TableTRView'导入TableDataTR;const TableView = ({ thds, tableData }) =>{如果(!thds){返回<table></table>;}返回 (<div><表格><头><tr>{thds.map((data, i) => {data.th} )}</tr></thead><TableDataTR tableData={tableData}/>
)}导出默认的 TableView;
表格打印了头部,但我在打印 tbody
时遇到问题:
import React, { Component } from 'react';类 TableDataTR 扩展组件 {使成为() {让行 = this.props.tableData.map((currElement, index) =>{返回(<tr key={index}><td>currElement[index]</td></tr>)});返回 (<tbody>{行}</tbody>);}}导出默认 TableDataTR;
示例数据,表头
thds : [ { th: 'th1' },{ th: 'th2' }]tableData:[ { tdData1: 'somedata', tdData2: 'somedata2' },{ tdData1: 'somedata', tdData2: 'somedata2' },]
表头工作正常,但是tbody
里面的数据根本不显示.
最终目标是获取任意 2 个数组并相应地显示表格.
<td>..</td>
部分再次出现拼写错误,缺少 {}
用于您的表达.对于第一次映射后的动态解决方案,您还需要映射您的对象.
<td>{Object.keys(currElement).map(key => currElement[key])}</td></tr>I want to create entire table from a JSON array include dynamic th
s, so a decoupled the head part to:
import React from 'react';
import TableDataTR from './TableTRView';
const TableView = ({ thds, tableData }) => {
if (!thds) {
return <table></table>;
}
return (
<div>
<table>
<thead>
<tr>
{thds.map((data, i) => <th key={i}>{data.th}</th>)}
</tr>
</thead>
<TableDataTR tableData={tableData}/>
</table>
</div>
)
}
export default TableView;
And the table prints the head part, but I am having trouble printing my tbody
:
import React, { Component } from 'react';
class TableDataTR extends Component {
render() {
let rows = this.props.tableData.map((currElement, index) =>{
return(
<tr key={index}>
<td>currElement[index]</td>
</tr>
)
});
return (
<tbody>{rows}</tbody>
);
}
}
export default TableDataTR;
Example data, table head
thds : [ { th: 'th1' },
{ th: 'th2' }]
tableData:[ { tdData1: 'somedata', tdData2: 'somedata2' },
{ tdData1: 'somedata', tdData2: 'somedata2' },]
The table head works fine, but the data inside tbody
is not displaying at all.
The final goal is to get any 2 arrays and display the table accordingly.
解决方案 There is a typo again in your <td>..</td>
part, missing {}
for your expression. For the dynamic solution after first map you need to map your Objects as well.
<tr key={index}>
<td>
{
Object.keys(currElement).map(key => currElement[key])
}
</td>
</tr>
这篇关于完全动态地从 JSON 创建一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文
登录
关闭
扫码关注1秒登录
发送“验证码”获取
|
15天全站免登陆