帮我写一个可编辑表格的react组件
时间: 2024-05-15 21:16:45 浏览: 115
React-editable-table:从头开始React可编辑表格
以下是一个可编辑表格的React组件示例:
```
import React, { useState } from "react";
const EditableTable = ({ data }) => {
const [tableData, setTableData] = useState(data);
const handleTableInputChange = (e, rowIdx, colIdx) => {
const { value } = e.target;
const newTableData = [...tableData];
newTableData[rowIdx][colIdx] = value;
setTableData(newTableData);
};
return (
<table>
<thead>
<tr>
{tableData[0].map((col, colIdx) => (
<th key={`col-${colIdx}`}>{col}</th>
))}
</tr>
</thead>
<tbody>
{tableData.slice(1).map((row, rowIdx) => (
<tr key={`row-${rowIdx}`}>
{row.map((col, colIdx) => (
<td key={`cell-${rowIdx}-${colIdx}`}>
<input
type="text"
value={col}
onChange={(e) => handleTableInputChange(e, rowIdx + 1, colIdx)}
/>
</td>
))}
</tr>
))}
</tbody>
</table>
);
};
export default EditableTable;
```
该组件接受一个数据参数(格式为二维数组),并生成一个可编辑的表格。当输入框的值改变时,会更新相应的单元格数据并重新渲染表格。
使用方法:
```
import EditableTable from "./EditableTable";
const data = [
["Name", "Age", "Gender"],
["John", "30", "Male"],
["Jane", "25", "Female"],
];
function App() {
return <EditableTable data={data} />;
}
export default App;
```
阅读全文