使用箭头键导航/选择网格表行



我正试图在react应用程序上导航ag网格表的行。这意味着当我向上或向下按时,当前选定的行将变为上一行/下一行。

我已经在ag网格文档上尝试过这个例子。但我不知道如何访问gridOptions。我该怎么做?

我想我找到了一种方法,尽管我使用的是useRef,我更喜欢避免它。

这是主要功能:

const arrowKeysNavigation = (tableRef) => (params) => {
var previousCell = params.previousCellPosition;
var suggestedNextCell = params.nextCellPosition;
const api = tableRef.current.api;
var KEY_UP = 38;
var KEY_DOWN = 40;
var KEY_LEFT = 37;
var KEY_RIGHT = 39;
switch (params.key) {
case KEY_DOWN:
previousCell = params.previousCellPosition;
// set selected cell on current cell + 1
api.forEachNode(function (node) {
if (previousCell.rowIndex + 1 === node.rowIndex) {
node.setSelected(true);
}
});
return suggestedNextCell;
case KEY_UP:
previousCell = params.previousCellPosition;
// set selected cell on current cell - 1
api.forEachNode(function (node) {
if (previousCell.rowIndex - 1 === node.rowIndex) {
node.setSelected(true);
}
});
return suggestedNextCell;
case KEY_LEFT:
case KEY_RIGHT:
return suggestedNextCell;
default:
throw new Error(
"this will never happen, navigation is always one of the 4 keys above"
);
}
};

主要步骤:

  1. 创建引用const tableRef = React.useRef();
  2. 将其与上面的函数一起关联到ag网格:

<AgGridReact ... ref={tableRef} navigateToNextCell={arrowKeysNavigation(tableRef)}/>

最新更新