首页 > 解决方案 > 使用箭头键导航/选择 ag-grid 表行

问题描述

我正在尝试在反应应用程序上导航 ag-grid 表的行。这意味着当我向上或向下按时,当前选定的行将更改为上一行/下一行。

我已经尝试了ag-grid docs上的示例。但我不知道如何访问 gridOptions。我将如何进行这项工作?

标签: reactjsnavigationag-grid

解决方案


我想我找到了一种方法,尽管我正在使用 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-grid:

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


推荐阅读