在 React 16.11.0 中,我使用 map()
函数作为一个简单的 JSON 对象来访问每个元素的值。当 ReactDOM 呈现 content
时,表格将显示 列 中 data
的每个元素的值列表:
const data = [
{ Name: "Jame", Email: "jame123@gmail.com", ID: "1568132456", City: "New York" },
{ Name: "Harris", Email: "harris456@yahoo.com", ID: "7666487798", City: "Chicago" },
{ Name: "Daisy", Email: "daisy789@hotmail.com", ID: "2177897432", City: "Los Angeles" },
// etc...
];
const Table = ({data}) => {
const head = (
<tr>
<th>Name</th>
<th>Email</th>
<th>ID</th>
<th>City</th>
</tr>
);
const body = data.map(element => (
<tr key={element.ID}>
<td>{element.Name}</td>
<td>{element.Email}</td>
<td>{element.ID}</td>
<td>{element.City}</td>
</tr>
));
return (
<table>
<thead>{head}</thead>
<tbody>{body}</tbody>
</table>
);
};
ReactDOM.render(<Table data={data}/>, document.querySelector('div'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div></div>
表输出将在下面显示这些值:
相反,我想要的是值将显示在
行 中,如下表所示:
在这种情况下如何转换表格?
为每一行创建规则并在这些行上循环,然后在您的数据上循环:
const data = [
{ Name: "Jame", Email: 'jame123@gmail.com', ID: "1568132456", City: "New York" },
{ Name: "Harris", Email: 'harris456@gmail.com', ID: "7666487798", City: "Chicago" },
{ Name: "Daisy", Email: 'daisy789@gmail.com', ID: "2177897432", City: "Los Angeles" },
// etc...
];
const rows = [
{ name: 'Name', render: (item) => item.Name },
{ name: 'Email', render: (item) => item.Email },
{ name: 'ID', render: (item) => item.ID },
{ name: 'City', render: (item) => item.City },
];
const body = rows.map(({ name, render }) => (
<tr key={name}>
<td>{name}</td>
{data.map((item, i) => (
<td key={i}>{render(item)}</td>
))}
</tr>
));
const content = (
<div>
<table>
<tbody>{body}</tbody>
</table>
</div>
);
我是一名优秀的程序员,十分优秀!