Renders a table with rows dynamically created from an array of primitives.
- Render a
<table>
element with two columns (ID
andValue
). - Use
Array.prototype.map
to render every item indata
as a<tr>
element, consisting of its index and value, give it akey
produced from the concatenation of the two.
代码实现
function DataTable({ data }) {
return (
<table>
<thead>
<tr>
<th>ID</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{data.map((val, i) => (
<tr key={`${i}_${val}`}>
<td>{i}</td>
<td>{val}</td>
</tr>
))}
</tbody>
</table>
);
}
使用样例
const people = ['John', 'Jesse'];
ReactDOM.render(<DataTable data={people} />, document.getElementById('root'));