0

I have difficulties for completing an emerging task. I must implement a table in which some columns must have two fields. These columns must have a sorting functionality through which the user will be able to sort the selected fields. To be more accurate, see the screenshot below:

enter image description here

You can see the columns which contains two fields. When, the user clicks in a field, arrows must be shown and the grid will be sorted by the selected value. When the user clicks the other fields (Price for example), arrows are shown, the field becomes bold and the grid is sorted by the selected field.

I use Griddle but, how can I implement in Griddle such a functionality? Should I make my own grid from scratch?

4

1 回答 1

1

This will sort any column if you have stored your data in the state and the data is either a string, number or boolean.

function sortFunc(a, b, key) {
  
  if (typeof(a[key]) === 'number') {
    return a[key] - b[key];
  } else if (typeof(a[key]) === 'boolean') {
    return a[key] ? 0 : 1;
  }

  const ax = [];
  const bx = [];

  a[key].replace(/(\d+)|(\D+)/g, (_, $1, $2) => { ax.push([$1 || Infinity, $2 || '']); });
  b[key].replace(/(\d+)|(\D+)/g, (_, $1, $2) => { bx.push([$1 || Infinity, $2 || '']); });

  while (ax.length && bx.length) {
    const an = ax.shift();
    const bn = bx.shift();
    const nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
    if (nn) return nn;
  }

  return ax.length - bx.length;
}

function sortByColumn(column, data) {
      const isAsc = this.state.sortHeader === column ? !this.state.isAsc : true;
      const sortedData = data.sort((a, b) => sortFunc(a, b, column));

      if (!isAsc) {
        sortedData.reverse();
      }

      this.setState({
        data: sortedData,
        sortHeader: column,
        isAsc
      });
  }
<IconButton onClick={() => this.sortByColumn(column.key, this.state.data)} style={styles.sortButton} >
  <SortIcon />
</IconButton>

于 2017-06-21T14:02:11.267 回答