如何在React-Table中添加可排序的索引列

5

我想使用react-table创建一个可排序的列,该列会为每一行分配一个编号(根据其在数据集中的位置)。

根据文档,通过比较accessor值的排序函数来实现排序。但是,accessor选项不公开索引,而Cell选项则公开索引。

所以这意味着这样做是行不通的:

const columns = [
  {
    Header: '#',
    id: 'index',
    accessor: (row) => row.index // 'index' is undefined
  },
  /* ... */
]

我的当前解决方法是直接将索引注入到数据集中,像这样:

myIndexedData = myData.map((el,index) => ({index, ...el})) //immutable

return (
  <ReactTable
    data={myIndexedData}
    columns={columns}
  />
);

这并不是一个最优解,尤其是在处理大型数据集时。我是否有没有看到的更好的方法?

5个回答

9
您可以使用第二个参数作为索引。
{
      Header: '#',
      id: 'index',
      accessor: (_row: any, i : number) => i + 1 
}

大师回答,解决了我的问题! - Daniel Danielecki
这适用于v7.7.0。 - Ronald Das

7
{
    Header: "",
    id: "row",
    maxWidth: 50,
    filterable: false,
    Cell: (row) => {
        return <div>{row.index}</div>;
    }
},

row.index 仍未定义。 - Ajay Ghosh

5
{
    Header: "Index",
    accessor: "",
    Cell: (row) => {
        return <div>{row.row.id + 1}</div>;
    },
    disableSortBy: true,
    disableFilters: true,
},

版本号:"react-table": "^7.6.3"


请问您能否帮忙解释一下为什么使用那个特定版本可能会解决这个问题? - Sijan Shrestha
只需将row.row.id转换为Number(row.row.id),这样它就不会显示为11、21、31...了。 - javasenior

1
   {
      Header: '#',
      Cell: (row) => {
        return <div>{Number(row.row.id) + 1}</div>;
      },
    }

"react-table": "7.7.0",获取分页和页面大小的索引
function getIndex(props) {
  return (
     <div>
       {props.state.pageIndex * props.state.pageSize + 
        Number(props.row.id) + 1}
     </div>
  );
}

0
export const SerialNumberColumn = {
    Header: "Sr No", // label of header
    id: "row", 
    maxWidth: 50,
    filterable: false,  
    Cell: (row) => {
      let {pageIndex} = row.state; // get current page index (1 - n)
      let {index} = row.cell.row;  // get current row number (0 - 9)
      let srNo = ``;

      if(pageIndex === 1){
        srNo = index + 1;
      // 1, 2, 3, 4,
     // as index starts from 0

      }else{
        if(index === 9){
          srNo = `${pageIndex}0`;
       // in case of 20, 30, 40, 50
        }else{
          srNo = `${pageIndex - 1}${index + 1}`;
       // for others such as 11, 12, 13, 41, 42, ..., n
        }
      }
        return <div>{srNo}</div>;
    }
};

例如,您的页面大小为10(每页10行),总共有15页。因此,总记录数将为10 * 15 = 150;

上述代码的作用是,

  1. let {pageIndex} = row.**strong text**state;

这个提取每一行的页码。 因此,从记录0-9开始,页码将为1

  1. let {index} = row.cell.row;

获取行号

因此,第一行为0,第二行为1,以此类推。 对于每一页,我们将获得恰好0-9条记录或更少,因为页面大小为10。

  1. 由于行号从0开始,因此我们将其增加1。
if(pageIndex === 1){
        srNo = index + 1;

// srNo = 0 + 1 -> 1
// srNo = 1 + 1 -> 2

从第二页开始,当行号为9时,序号应为20、30、40。
行号 | 序列号 0 11 1 12 2 13 . . . . . . 9 20
因此我们将只使用 pageIndex 为0。
          srNo = `${pageIndex}0`; 
// srNo = 20
// srNo = 30
// srNo = 40
  1. 最后,对于第一页之后的剩余序列号,将是 srNo =`${pageIndex - 1}${index + 1}`;

例如:

srNo = `${2 - 1}${0 + 1}`; 11


不仅提供代码,还请在代码中加入注释,解释代码的工作原理或者如何回答问题。 - Someone Special

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接