想直接看实现?可以参考以下示例
全局分面允许您为表中所有列的数据生成值列表。例如,可以从所有行、所有列中生成表中唯一值的列表,用作自动完成筛选器组件中的搜索建议。或者,可以从数字表中生成最小和最大值的元组,用作范围滑块筛选器组件的范围。
要使用任何全局分面功能,您必须在表选项中包含相应的行模型。
//only import the row models you need
import {
getCoreRowModel,
getFacetedRowModel,
getFacetedMinMaxValues, //depends on getFacetedRowModel
getFacetedUniqueValues, //depends on getFacetedRowModel
} from '@tanstack/react-table'
//...
const table = useReactTable({
// other options...
getCoreRowModel: getCoreRowModel(),
getFacetedRowModel: getFacetedRowModel(), //Faceting model for client-side faceting (other faceting methods depend on this model)
getFacetedMinMaxValues: getFacetedMinMaxValues(), //if you need min/max values
getFacetedUniqueValues: getFacetedUniqueValues(), //if you need a list of unique values
//...
})
//only import the row models you need
import {
getCoreRowModel,
getFacetedRowModel,
getFacetedMinMaxValues, //depends on getFacetedRowModel
getFacetedUniqueValues, //depends on getFacetedRowModel
} from '@tanstack/react-table'
//...
const table = useReactTable({
// other options...
getCoreRowModel: getCoreRowModel(),
getFacetedRowModel: getFacetedRowModel(), //Faceting model for client-side faceting (other faceting methods depend on this model)
getFacetedMinMaxValues: getFacetedMinMaxValues(), //if you need min/max values
getFacetedUniqueValues: getFacetedUniqueValues(), //if you need a list of unique values
//...
})
一旦在表选项中包含了相应的行模型,您将能够使用分面表实例 API 来访问分面行模型生成的值列表。
// list of unique values for autocomplete filter
const autoCompleteSuggestions =
Array.from(table.getGlobalFacetedUniqueValues().keys())
.sort()
.slice(0, 5000);
// list of unique values for autocomplete filter
const autoCompleteSuggestions =
Array.from(table.getGlobalFacetedUniqueValues().keys())
.sort()
.slice(0, 5000);
// tuple of min and max values for range filter
const [min, max] = table.getGlobalFacetedMinMaxValues() ?? [0, 1];
// tuple of min and max values for range filter
const [min, max] = table.getGlobalFacetedMinMaxValues() ?? [0, 1];
如果您选择不使用内置的客户端分面功能,而是可以在服务器端实现自己的分面逻辑,并将分面值传递给客户端。您可以使用 `getGlobalFacetedUniqueValues` 和 `getGlobalFacetedMinMaxValues` 表选项来从服务器端解析分面值。
const facetingQuery = useQuery(
'faceting',
async () => {
const response = await fetch('/api/faceting');
return response.json();
},
{
onSuccess: (data) => {
table.getGlobalFacetedUniqueValues = () => data.uniqueValues;
table.getGlobalFacetedMinMaxValues = () => data.minMaxValues;
},
}
);
const facetingQuery = useQuery(
'faceting',
async () => {
const response = await fetch('/api/faceting');
return response.json();
},
{
onSuccess: (data) => {
table.getGlobalFacetedUniqueValues = () => data.uniqueValues;
table.getGlobalFacetedMinMaxValues = () => data.minMaxValues;
},
}
);
在此示例中,我们使用 `react-query` 中的 `useQuery` hook 从服务器获取分面数据。数据获取完成后,我们将 `getGlobalFacetedUniqueValues` 和 `getGlobalFacetedMinMaxValues` 表选项设置为返回服务器响应中的分面值。这将使表能够使用服务器端分面数据来生成自动完成建议和范围筛选器。
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。