antd design 可搜索列的表单的封装
技术栈:react hooks
需求描述:
这样的一份表格,就有些列希望是可以搜索的比如这样:
实操过程:
在antd design官网有案例https://ant.design/components/table-cn/#components-table-demo-drag-sorting
但是官网案例代码的不太符合公司的技术栈,需要做些改动和封装,毕竟需要使用的页面很多,把这些功能单独做成函数组件方便日后的使用和维护。
函数组件的代码:
import React, { useState } from 'react';
import { Input, Button, Space } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
function GetColumnSearchProps(dataIndex) {
const [state, setState] = useState({
searchText: '',
searchedColumn: '',
});
function handleSearch(selectedKeys, confirm, dataIndex) {
confirm();
setState({
// 这个state里面存的是搜索弹出的时候输入框里面的内容,searchText是输入的信息,searchedColumn是该列的字段名
...state,
searchText: selectedKeys[0],
searchedColumn: dataIndex,
});
};
function handleReset(clearFilters) {
clearFilters();
setState({ ...state, searchText: '', searchedColumn: '' });
};
let searchInput;
return ({
// 可以自定义筛选菜单,此函数只负责渲染图层,需要自行编写各种交互
filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) =>
(
<div style={{ padding: 8 }}>
<Input
ref={node => {
searchInput = node;
}}
placeholder={`Search ${dataIndex}`}
value={selectedKeys[0]}
onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
style={{ width: 188, marginBottom: 8, display: 'block' }}
/>
<Space>
<Button
type="primary"
onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
icon={<SearchOutlined />}
size="small"
style={{ width: 90 }}
>
Search
</Button>
<Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
Reset
</Button>
</Space>
</div>
),
// 自定义 filter 图标。
filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
// 本地模式下,确定筛选的运行函数
onFilter: (value, record) =>
record[dataIndex]
? record[dataIndex]
.toString()
.toLowerCase()
.includes(value.toLowerCase())
: '',
// 自定义筛选菜单可见变化时调用
onFilterDropdownVisibleChange: visible => {
if (visible) {
setTimeout(() => searchInput.select(), 100);
}
},
// (text, record, index)分别为当前行的值,当前行数据,行索引
render: text =>
state.searchedColumn === dataIndex ? (
<p style={{ backgroundColor: '#ffc069', padding: 0 }}>{text}</p>
) : (
text
),
});
}
export {GetColumnSearchProps} ;
具体的使用:
引入该函数组件:具体的位置视项目而定。
import {GetColumnSearchProps} from '@/utils/getColumnSearchProps';
然后在columns
里面引用就行:
实际上GetColumnSearchProps()
函数执行返回的是对象,所以在调用的时候用拓展运算(...
)符将其在语法层面展开。
{
title: '供应商名称',
dataIndex: 'accountName',
width: '150px',
editable: true,
sorter: (a, b) => a.accountName.localeCompare(b.accountName, 'zh'),
...GetColumnSearchProps('accountName'),
},
{
title: '供应商代码',
dataIndex: 'supplierCode',
width: '150px',
editable: true,
sorter: (a, b) => a.supplierCode.localeCompare(b.supplierCode, 'zh'),
...GetColumnSearchProps('supplierCode'),
},