使用 react 写一个普通表格
以下是一个使用 React 写的普通表格示例:
import React from "react";
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{ name: "John", age: 25, email: "john@example.com" },
{ name: "Jane", age: 30, email: "jane@example.com" },
{ name: "Bob", age: 35, email: "bob@example.com" },
{ name: "Alice", age: 40, email: "alice@example.com" }
]
};
}
render() {
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{this.state.data.map((item, index) => (
<tr key={index}>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.email}</td>
</tr>
))}
</tbody>
</table>
);
}
}
export default Table;
在上面的代码中,我们使用了一个名为 Table 的类组件来创建表格。在构造函数中,我们初始化了 data 状态,它是一个包含了表格数据的数组。
在 render 方法中,我们使用 <table>、<thead>、<tbody> 和 <tr> 等 HTML 元素来渲染表格。我们还使用了 map 方法来遍历 data 数组,并为每个条目创建一个 <tr> 元素。最后,我们在每个 <tr> 元素中渲染出该条目的 name、age 和 email 属性。
我们可以在其他组件中导入 Table 并将其渲染到页面中,就像这样:
import React from "react";
import Table from "./Table";
function App() {
return (
<div>
<h1>My Table</h1>
<Table />
</div>
);
}
export default App;
这将在页面上渲染出一个简单的表格
原文地址: https://www.cveoy.top/t/topic/c9eF 著作权归作者所有。请勿转载和采集!