// 'zero' is the ID of a row that is checked.
const [ selected, setSelected ] = React.useState( [ 0 ] );
解决方案
/**
* Sort function.
*/
function SortCheckedAtTop( rows ) {
let ids = rows.map( ( row ) => row.id );
// Spread operator is used to avoid overwriting the original sort order of `rows`.
// You might want to preserve the original sort order of `rows` to use it later.
// in this function.
let resorted = [ ...rows ].sort(
( a, b ) => {
// Display the checked rows first.
let ai = selected.indexOf( a.id ); // Index for row a.
// If a.id is not in the selected list ai will be -1.
// If -1, update ai by placing it at the end of the list of
// selected rows. The end position is calculated using
// ( selected.length ).
// But we need to maintain the original order of unselected rows.
// So, we add the position index from the original rows array:
// ( ids.indexOf( a.id ) ).
// If the selected list had 4 IDs, 'a' was not selected,
// and a.id were in position 3 in the original list of rows
// (zero-based array index = 2), ai would be 4 + 2 = 6.
// This maintains the same order as the original list of rows.
ai = ai === -1 ? selected.length + ids.indexOf( a.id ) : ai;
// Update bi if needed.
let bi = selected.indexOf(b); // Index for row b.
bi = bi === -1 ? selected.length + ids.indexOf( b.id ) : bi;
// Return the sort result.
// negative value: ascending,
// positive value: descending,
// zero: undetermined (you can add more code to sort by another sort key)
return ai - bi;
}
);
return resorted;
}
1条答案
按热度按时间gmol16391#
下面给出了一个解决方案,即函数SortCheckedAtTop。要使该解决方案正常工作,需要将行列表表示为对象数组(
rows
)。需要使用行ID数组来维护选中行的列表(selected
)。rows
和selelcted
都应该使用某种状态管理方法来维护(例如Redux,React.useState,React.useReducer等)。一般的排序可以使用JavaScript的Intl.Collator来处理。例如:
函数SortCheckedAtTop基于这里的排序函数。该函数假设rows是之前排序的对象列表。对象可能看起来像这样:
selected
是id
的数组,表示被检查的行。如果使用React.useState
来管理这个数组,您可能会有一个类似于以下的语句:解决方案