您好,登錄后才能下訂單哦!
要在React中創(chuàng)建可復(fù)用且靈活的表格組件,支持自定義列、搜索和分頁(yè),可以按照以下步驟進(jìn)行:
以下是一個(gè)簡(jiǎn)單的示例代碼,演示了如何在React中創(chuàng)建一個(gè)可復(fù)用的表格組件:
import React, { useState } from 'react';
const Table = ({ data, columns }) => {
const [searchTerm, setSearchTerm] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 5;
const filteredData = data.filter((item) =>
Object.values(item).some((value) =>
value.toString().toLowerCase().includes(searchTerm.toLowerCase())
)
);
const paginatedData = filteredData.slice(
(currentPage - 1) * itemsPerPage,
currentPage * itemsPerPage
);
return (
<div>
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<table>
<thead>
<tr>
{columns.map((column) => (
<th key={column}>{column}</th>
))}
</tr>
</thead>
<tbody>
{paginatedData.map((item, index) => (
<tr key={index}>
{columns.map((column) => (
<td key={column}>{item[column]}</td>
))}
</tr>
))}
</tbody>
</table>
<div>
<button
onClick={() => setCurrentPage(currentPage - 1)}
disabled={currentPage === 1}
>
Prev
</button>
<span>{currentPage}</span>
<button
onClick={() => setCurrentPage(currentPage + 1)}
disabled={currentPage === Math.ceil(filteredData.length / itemsPerPage)}
>
Next
</button>
</div>
</div>
);
};
export default Table;
在父組件中使用Table組件并傳入數(shù)據(jù)和列定義:
import React from 'react';
import Table from './Table';
const data = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 },
{ id: 4, name: 'David', age: 40 },
];
const columns = ['id', 'name', 'age'];
const App = () => {
return <Table data={data} columns={columns} />;
};
export default App;
通過(guò)以上步驟,您就可以在React中創(chuàng)建一個(gè)可復(fù)用且靈活的表格組件,支持自定義列、搜索和分頁(yè)功能。您可以根據(jù)實(shí)際需求對(duì)表格組件進(jìn)行定制和擴(kuò)展,以滿足不同場(chǎng)景下的需求。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。