自定义过滤方法反应表,同一列上有两种不同的匹配类型



我有一个表,其中包含tld的列表,可以通过搜索框或特定类别的按钮进行筛选。按钮根据tld的列表进行过滤,而搜索框应该与tld模糊匹配。

const columns = useMemo(
() => [
{
Header: 'TLD',
accessor: 'tld',
filter: multiFilter,
Cell: (props) => {
const onSale = props.row.original.sale
return (
<div>
.{props.value} {onSale ? <span className="font-bold text-purple m-left-1">Sale</span> : null}
</div>
)
},
},

按钮过滤

<button autoFocus className="py-1 px-4 text-sm focus:bg-blue focus:rounded-full" onClick={() => setFilter('tld', undefined)}>All</button>
<button className="py-1 px-4 text-sm focus:bg-blue focus:rounded-full" onClick={() => setFilter('tld', sale)}>Sale</button>

搜索框过滤

<input id="tld-search-box" value={searchFilterInput} onChange={handleSearchFilterChange} placeholder={'Enter a domain extension here'} className="border border-gray-300 p-2 w-[640px] rounded-full" />

对于按钮,我不得不制作一个自定义的过滤方法

function multiFilter(rows, columnIds, filterValue) {
return filterValue.length === 0
? rows
: rows.filter((row) =>
filterValue.includes(String(row.original[columnIds])),
);
}

这是最终使用setFilter的搜索过滤方法,因此它最终也会通过自定义过滤方法

const handleSearchFilterChange = (e) => {
const value = e.target.value || undefined
const trimmedValue = value ? value.replace(/^./g, '') : undefined
setFilter('tld', trimmedValue)
setSearchFilterInput(value)
}

我遇到的问题是,由于他们最终都使用了自定义筛选方法,因此搜索框筛选与includes方法filterValue.includes(String(row.original[columnIds])),完全匹配。我希望搜索框与任何包含输入值的内容相匹配,但我不确定如何做到这一点,因为它们都作用于列。如有任何建议,我们将不胜感激。

我想全局过滤也可以解决这个问题,但我最终发现这两种搜索类型是不同的JS类型。按钮是类型对象,而搜索栏是字符串,所以这解决了问题:

function multiFilter(rows, columnIds, filterValue) {
return filterValue.length === 0 ? rows : rows.filter((row) => {
let match = String(row.original[columnIds])
return typeof filterValue === 'object'
? filterValue.includes(match) // Check to see if match is in array
: match.includes(filterValue) // do sub string match for strings
})
}

最新更新