对不起,标题不好,但是我不确定如何用Google搜索这个问题。无论出于什么原因,我都难以理解如何在reactjs中创建该表。第1列下的XX为空,而第2列中的数据将继续填充。
这就是我想要的:xx为空白
column 1 column 2
1. David Male
xx 30
xx BasketBall
2. Sam BaseBall
3. John Male
xx Football
我正在尝试使用reactjs和material-ui做到这一点。
我的数据格式:
[
['David', ['Male', '30', 'BasketBall']],
['Sam', ['BaseBall']],
['John', ['Male', 'FootBall']]
]
这是我的代码的片段:
<TableBody>
//this will display 1 row for 1 item as in number 2 mentioned above.
{data.map((prop, key) => {
if (prop[1].length <= 1) {
return (
<TableRow key={key}>
{prop.map((prop, key) => {
return (
<TableCell className={classes.tableCell} key={key}>
{prop}
</TableCell>
);
})}
</TableRow>
);
} else {
//this is where I'm stuck at
return (
<TableRow key={key}>
{prop.map((prop, key) => {
return (
<TableCell className={classes.tableCell} key={key}>
{prop}
</TableCell>
);
})}
</TableRow>
);
}
})}
</TableBody>
答案 0 :(得分:1)
一种解决方案是检查该值是否为数组。如果是这样,则将每个数组值映射到div
中(逐行显示它们)。否则,仅输出prop
。
我为vertical-align: top
添加了一个内联样式,但是您可能希望将其移动到CSS文件中。
//this is where I'm stuck at
return (
<tr key={key}>
{prop.map((prop, key) => (
<td
key={key}
style={{verticalAlign: 'top'}}
>
{Array.isArray(prop) && prop.map((prop, key) => (
<div key={key}>{prop}</div>
))
|| prop}
</td>
))}
</tr>
);
答案 1 :(得分:0)
我将转换数据,以便可以轻松呈现它。
这是我要怎么做:
const tabularizeData = data =>
data.reduce((acc, item, index) => {
let curName;
const name = item[0]
const stuff = item[1]
for (const i in stuff) {
const thing = stuff[i]
if (i > 0) {
acc.push(['', '', thing])
} else {
acc.push([index, name, thing])
}
}
return acc
}, [])
这样会转换您的数据:
const data = [
['David', ['Male', '30', 'BasketBall']],
['Sam', ['BaseBall']],
['John', ['Male', 'FootBall']]
]
tabularizeData(data)
[
[0, "David", "Male"]
["", "", "30"]
["", "", "BasketBall"]
[1, "Sam", "BaseBall"]
[2, "John", "Male"]
["", "", "FootBall"]
]
现在创建表应该很容易。希望这会有所帮助!