在react-table中使用id进行搜索,可以通过以下步骤实现:
npm install react-table
import React, { useMemo } from 'react';
import { useTable, useGlobalFilter } from 'react-table';
const Table = ({ columns, data }) => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
state,
setGlobalFilter,
} = useTable(
{
columns,
data,
},
useGlobalFilter
);
const { globalFilter } = state;
const handleSearch = (e) => {
const value = e.target.value || '';
setGlobalFilter(value.toLowerCase());
};
return (
<div>
<input
type="text"
value={globalFilter || ''}
onChange={handleSearch}
placeholder="Search by ID"
/>
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
))}
</tr>
);
})}
</tbody>
</table>
</div>
);
};
const App = () => {
const columns = useMemo(
() => [
{
Header: 'ID',
accessor: 'id', // 使用id作为访问器
},
// 其他列定义
],
[]
);
const data = useMemo(
() => [
{ id: 1, name: 'John Doe', age: 25 },
{ id: 2, name: 'Jane Smith', age: 30 },
// 其他数据
],
[]
);
return (
<div>
<h1>React Table Example</h1>
<Table columns={columns} data={data} />
</div>
);
};
这样,你就可以在react-table中使用id进行搜索了。输入框会根据输入的id值进行过滤,并显示匹配的行数据。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云