【问题标题】:Why is my custom sort not working with Material-UI Data Grid component?为什么我的自定义排序不适用于 Material-UI 数据网格组件?
【发布时间】:2021-10-14 07:59:58
【问题描述】:

我已经实现了 Material-UI 的数据网格组件,从我的 API 带回的 JSON 数组中获取数据,并且必须实现 RenderCell 函数来解决文本溢出问题并呈现一个按钮以将用户带到单独的页面.我还实现了他们的 ValueGetter 以提取到 Excel 文档和进一步的功能,如果它们是未定义的或 null 则将值转换为空字符串,因此实现了他们文档中指定的自定义 sortComparator 函数。

但是,无论我对 sortComparator 使用什么实现,如果有空单元格,它们在升序排序期间放置在顶部附近,但在降序排序期间正确放置,但如果所有单元格都已填充,则排序工作为有意的。

我希望我的数据网格在排序期间将所有空单元格放在底部,无论是升序还是降序。

自定义排序尝试:

    const customSort = (a: GridCellValue, b: GridCellValue) =>
    {
        if(a === '') {
           return 0;
        }
        else {
            return b > a ? -1 : 1;
    }

【问题讨论】:

    标签: json reactjs typescript sorting material-ui


    【解决方案1】:

    根据MDN

    如果a和b是两个被比较的元素,那么:

    1. 如果 compareFunction(a, b) 返回的值 > 大于 0,则将 b 排在 a 之前。
    2. 如果 compareFunction(a, b) 返回的值 ≤ 0,则保持 a 和 b 的顺序相同。

    因此,请注意,如果您希望底部有空单元格,则不应返回 0。

    您还应该对升序和降序使用两个不同的 customSort 函数。

    const customSortAsc = (a,b) => {
      if(a === '') return 1;
      if(b === '') return -1;
      if(a > b) return 1
      if(a < b) return -1;
      if(a === b) return 0;
    }
    
    const customSortDesc = (a,b) => {
      if(a === '') return 1;  // Not needed line, here for clarification
      if(b === '') return -1; // Not needed line, here for clarification
      if(a > b) return -1
      if(a < b) return 1;
      if(a === b) return 0;
    }
    
     const initialArray = ['','ddd','aaa','','ccc','bbb',''];
    
     const sortedArrayAsc = [...initialArray].sort(customSortAsc);
     // sortedArrayAsc = ['aaa','bbb','ccc','ddd','','','']
    
     const sortedArrayDesc = [...initialArray].sort(customSortDesc);
     // sortedArrayDesc = ['ddd','ccc','bbb','aaa','','','']
    
    

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 2020-07-18
      • 2022-07-28
      • 2022-01-20
      • 1970-01-01
      • 2020-03-22
      • 2021-12-29
      • 2020-09-24
      • 2020-09-29
      相关资源
      最近更新 更多