Как динамически навести курсор на элементы списка реагирования при нажатии клавиш со стрелками? - PullRequest
0 голосов
/ 05 января 2020

Я использую act-select и отображаю компонент Control как ноль, потому что у меня уже есть свой собственный ввод текста для пользовательского поиска. С моим пользовательским вводом, нулевым компонентом Control и остальными компонентамиact-select мой раскрывающийся список выглядит следующим образом:

img

Проблема заключается в том, что я не могу использовать клавиши со стрелками вверх и вниз для перемещения между результатами.

Я решил проверить, связана ли эта проблема с нулевым компонентом Control, однако после рендеринга поля ввода по умолчанию поле ввода стрелки вверх и вниз по-прежнему не работают, как они делают в своих демонстрациях в документах.

Я также пытался установить defaultValue={!!searchResults.length && searchResults[0]}, но это тоже не работает.

Что может Я тут делаю?

1 Ответ

0 голосов
/ 05 января 2020

Вот как я решил эту проблему:

export const addEventListenerArrowUpAndDown = () => {
  document.addEventListener("keydown", e => {
    // Make sure the drop down is open. In my case, it's shown only
    // when the length of my searchResults array is not 0
    const searchResultsExist = !!store.getState().search.searchResults.length;

    if (searchResultsExist) {
      // Pull all elements with a common class name from the drop down (all elements
      // usually have only this common class, the rest is too dynamic and unreliable)
      const searchResults = Array.from(
        document.getElementsByClassName("MuiListItem-root")
      );

      // I initially tried using .indexOf, but that didn't work, so I'm using this way
      let currentlyPseudoHoveredElement = -1;

      // See if one of the items already are "hovered" over
      searchResults.forEach((element, index) => {
        if (element.style.background === "rgba(85, 125, 146, 0.5)") {
          currentlyPseudoHoveredElement = index;
        }
      });

      // On Arrow Key down
      if (e.keyCode === 40 && !!searchResults.length) {
        if (
          currentlyPseudoHoveredElement !== -1 &&
          currentlyPseudoHoveredElement !== 4
        ) {
          // Set current background color to preferred color
          searchResults[currentlyPseudoHoveredElement].style.background =
            "#FFFFFF";
          // Set next element's background color to preferred color
          searchResults[currentlyPseudoHoveredElement + 1].style.background =
            "rgba(85, 125, 146, 0.5)";
        } else {
          searchResults[0].style.background = "rgba(85, 125, 146, 0.5)";
        }
      } 

      // On Arrow Key down
      else if (e.keyCode === 38) {
        if (
          currentlyPseudoHoveredElement !== -1 &&
          currentlyPseudoHoveredElement !== 0
        ) {
          // Set current background color to white
          searchResults[currentlyPseudoHoveredElement].style.background =
            "#FFFFFF";
          // Set previous element's background color to preferred color
          searchResults[currentlyPseudoHoveredElement - 1].style.background =
            "rgba(85, 125, 146, 0.5)";
        } else {
          searchResults[0].style.background = "rgba(85, 125, 146, 0.5)";
        }
      }
    }
  });
};

export const addEventListenerOnEnterOpenPseudoHoveredElement = () => {
  document.addEventListener("keydown", e => {
    if (e.keyCode === 13) {
      const searchResults = Array.from(
        document.getElementsByClassName("MuiListItem-root")
      );

      // In the event that the drop down is shown and one of the
      // elements is "hovered" over, open that URL that it points to
      // This also works if I use the actual mouse to hover over something; it will open the link this way
      searchResults.forEach((element, index) => {
        if (element.style.background === "rgba(85, 125, 146, 0.5)") {
          element.click();
        }
      });
    }
  });
};
...