英文:
How to map table rows in reactjs?
问题
在我尝试映射ID标题下的id
时,它是水平映射的,但我希望垂直映射。当我尝试将名称映射到名称标题下的value.user_name
时,相同的情况发生 - 它水平映射,但我想要垂直映射它们。
function App() {
let response = [
{
id: 134,
user_name: 'abc',
phone_number: 1234567890,
children: [
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
],
},
{
id: 948,
user_name: 'def',
phone_number: 9823437483,
children: [
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
],
},
{
id: 865,
user_name: 'abc',
phone_number: 1234567890,
children: [
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
],
},
];
console.log('response', response);
return (
<div className="App">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>phone number</th>
</tr>
</thead>
<tbody>
<tr>
{response.map((value, index) => {
return [<td>{value.id}</td>, <td>{value.user_name}</td>];
})}
</tr>
</tbody>
</table>
</div>
);
}
export default App;
英文:
When I am trying to map id
s below ID header it is mapping horizontally but I wanted to map in vertically. The same thing happens with value.user_name
when I am trying to map names below Name header — it maps horizontally but I want to map them vertically.
function App() {
let response = [
{
id: 134,
user_name: 'abc',
phone_number: 1234567890,
children: [
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
],
},
{
id: 948,
user_name: 'def',
phone_number: 9823437483,
children: [
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
],
},
{
id: 865,
user_name: 'abc',
phone_number: 1234567890,
children: [
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
{ id: 659, user_name: 'ghi', phone_number: 9834763467 },
],
},
];
console.log('response', response);
return (
<div className="App">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>phone number</th>
</tr>
</thead>
<tbody>
<tr>
{response.map((value, index) => {
return [<td>{value.id}</td>, <td>{value.user_name}</td>];
})}
</tr>
</tbody>
</table>
</div>
);
}
export default App;
答案1
得分: 3
你需要在map函数内部包含<tr>
,就像这样:
<tbody>
{response.map((value) => {
return (
<tr key={value.id}>
<td>{value.id}</td>
<td>{value.user_name}</td>
<td>{value.phone_number}</td>
</tr>
);
})}
</tbody>
现在的情况是,你的表格中只有一个tr
,这导致所有的td
元素都在同一行中渲染。
英文:
You need to include <tr>
inside the map function like this:
<tbody>
{response.map((value) => {
return (
<tr key={value.id}>
<td>{value.id}</td>
<td>{value.user_name}</td>
<td>{value.phone_number}</td>
</tr>
);
})}
</tbody>
What happens right now is you only have one tr
in the table, and that made all the td
elements to render in a single row.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论