想要跳过实现步骤?查看这些示例
全局分面允许您从表格数据中为所有列生成值列表。例如,可以从所有行和所有列生成表格中唯一值的列表,以用作自动完成过滤器组件中的搜索建议。或者,可以从数字表格生成最小值和最大值的元组,以用作范围滑块过滤器组件的范围。
为了使用任何全局分面功能,您必须在表格选项中包含适当的行模型。
//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;
},
}
);
在这个例子中,我们使用 useQuery hook 从 react-query 获取分面数据。一旦数据被获取,我们设置 getGlobalFacetedUniqueValues 和 getGlobalFacetedMinMaxValues 表格选项,以从服务器响应中返回分面值。这将允许表格使用服务器端分面数据来生成自动完成建议和范围过滤器。
您的每周 JavaScript 新闻。每周一免费发送给超过 100,000 名开发者。