在material-ui datagrid中实现搜索可以通过以下步骤完成:
import React, { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import TextField from '@mui/material/TextField';
const [searchKeyword, setSearchKeyword] = useState('');
const handleSearchKeywordChange = (event) => {
setSearchKeyword(event.target.value);
};
<TextField
label="Search"
value={searchKeyword}
onChange={handleSearchKeywordChange}
/>
const filterData = (data) => {
return data.filter((row) =>
Object.values(row).some(
(value) =>
value.toString().toLowerCase().includes(searchKeyword.toLowerCase())
)
);
};
<DataGrid rows={filterData(rows)} columns={columns} />
完整的示例代码如下:
import React, { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import TextField from '@mui/material/TextField';
const rows = [
{ id: 1, name: 'John Doe', age: 25 },
{ id: 2, name: 'Jane Smith', age: 30 },
{ id: 3, name: 'Bob Johnson', age: 35 },
];
const columns = [
{ field: 'id', headerName: 'ID', width: 70 },
{ field: 'name', headerName: 'Name', width: 150 },
{ field: 'age', headerName: 'Age', width: 70 },
];
const SearchableDataGrid = () => {
const [searchKeyword, setSearchKeyword] = useState('');
const handleSearchKeywordChange = (event) => {
setSearchKeyword(event.target.value);
};
const filterData = (data) => {
return data.filter((row) =>
Object.values(row).some(
(value) =>
value.toString().toLowerCase().includes(searchKeyword.toLowerCase())
)
);
};
return (
<div>
<TextField
label="Search"
value={searchKeyword}
onChange={handleSearchKeywordChange}
/>
<DataGrid rows={filterData(rows)} columns={columns} />
</div>
);
};
export default SearchableDataGrid;
这样,你就可以在material-ui datagrid中实现搜索功能了。
云+社区沙龙online第5期[架构演进]
企业创新在线学堂
云+社区技术沙龙[第17期]
企业创新在线学堂
Elastic 中国开发者大会
云原生正发声
领取专属 10元无门槛券
手把手带您无忧上云