首页 > 解决方案 > PrimeReact DataTable 使用 sortFunction 对列进行预排序

问题描述

我一直在尝试设置与此类似的预排序:https ://www.primefaces.org/primereact/showcase/#/datatable/sort

我面临的问题是,我想按具有我定义的 sortFunction 的列对渲染进行排序。

我有一个可用的 sortFunction,但如果我给 DataTable 一个 sortField,它就不会使用它。 在渲染时,空值在前面,这是可排序的默认排序,单击标题会使用正确的 sortFunction,它按字母顺序排序并将空值发送到末尾

是否有可能以某种方式解决这个问题,或者我应该放弃预分类?

编辑:我对数据进行了预排序并以这种方式将其提供给 DataTable,所以它可以工作,但它远非优雅,它也没有显示列在渲染时具有排序的箭头,但它可能对某人有帮助:

const  dataTableSortFunction  =  (value:  any[])  =>  (event:  ColumnSortParams):  any[]  =>  {
    return  [...value].sort((data1,  data2)  =>  {
        const  value1  =  data1[event.field];
        const  value2  =  data2[event.field];
        if  (value1  ==  null  &&  value2  ==  null)  return  0;
        if  (value2  ==  null)  return  -1;
        if  (value1  ==  null)  return  1;
        if  (typeof  value1  ===  "string"  &&  typeof  value2  ===  "string")
            return  value1.localeCompare(value2)  *  event.order;
         if  (value1  <  value2)  return  -1  *  event.order;
        if  (value1  >  value2)  return  1  *  event.order;
        return  0;
    });
};
const  myProductSort  =  dataTableSortFunction(products);
const  preSortedProducts  =  myProductSort({ field:  "category", order:  -1  });

...

<DataTable  value={preSortedProducts} className="p-datatable-sm">
    <Column  field="code"  header="Code"  sortable></Column>
    <Column  field="name"  header="Name"  sortable></Column>
    <Column
        field="category"
        header="Category"
        sortable
        sortFunction={myProductSort}
    ></Column>
    <Column  field="quantity"  header="Quantity"  sortable></Column>
    <Column  field="price"  header="Price"  sortable></Column>
</DataTable>

标签: sortingdatatableprimereact

解决方案


推荐阅读