如果你想在一个搜索框中输入关键字,并根据该关键字过滤表格中的单列(比如 username),你可以在 React 中使用状态(state)和事件处理函数来实现。
首先,在你的组件中定义一个状态变量来存储搜索关键字,同时创建一个事件处理函数来更新该状态变量的值。然后,根据搜索关键字过滤表格数据并渲染相应的结果。
以下是一个示例代码,展示了如何实现搜索框过滤表格的功能:
import React, { useState } from 'react';
function MyComponent() {
const [searchKeyword, setSearchKeyword] = useState('');
const [tableData, setTableData] = useState([
{ id: 1, username: 'user1' },
{ id: 2, username: 'user2' },
{ id: 3, username: 'user3' },
// 表格数据...
]);
const handleSearchChange = (event) => {
setSearchKeyword(event.target.value);
};
const filteredData = tableData.filter((data) =>
data.username.toLowerCase().includes(searchKeyword.toLowerCase())
);
return (
<div>
<input type="text" value={searchKeyword} onChange={handleSearchChange} placeholder="Search by username" />
<table>
<thead>
<tr>
<th>ID</th>
<th>Username</th>
</tr>
</thead>
<tbody>
{filteredData.map((data) => (
<tr key={data.id}>
<td>{data.id}</td>
<td>{data.username}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
在上述代码中,我们使用 useState 钩子创建了两个状态变量:searchKeyword 用于存储搜索关键字,tableData 用于存储表格数据。我们还定义了 handleSearchChange 函数来处理搜索框值的变化,并更新 searchKeyword 状态变量的值。
在表格渲染部分,我们使用 filter 方法根据搜索关键字过滤表格数据,并将过滤后的结果映射为表格行。
请根据你的具体需求和表格数据结构进行相应的调整。