javascript - 如何在 react 中使用向上和向下箭头键使下拉菜单工作

标签 javascript reactjs

我正在尝试使用 React 创建一个自定义下拉菜单,它也应该与键盘的上下键一起使用

这是我迄今为止尝试过的

import React, { useState, useEffect, useRef } from "react";
import "./dropdown.scss";

const Dropdown = ({ selected, setSelected }) => {
  const [open, setOpen] = useState(false);
  const options = ["Option1", "Option2", "Option3", "Option4"];
  const [cursor, setCurser] = useState(0);

  //   const label = ["frontend", "backend"];

  let menuRef = useRef();
  // let menuRef1 = useRef();

  useEffect(() => {
    let handler = (e) => {
      if (!menuRef.current.contains(e.target)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => {
      document.removeEventListener("mousedown", handler);
    };
  });

 

  const handleKeyDown = (e) => {
    if (e.keyCode === 38 && cursor > 0) {
      setCurser({
        ...cursor,
        cursor: cursor + 1,
      });
      console.log(cursor);
    } else if (e.keyCode === 40 && cursor < options.length - 1) {
      setCurser({
        ...cursor,
        cursor: cursor - 1,
      });
    }
  };
  return (
    <div>
      <div className="dropdown">
        <div
          ref={menuRef}
          onKeyPress={handleKeyDown}
          className={
            open ? "dropdown-wrapper--up dropdown-wrapper " : "dropdown-wrapper"
          }
        >
          <div className="dropdown-container">
            <div
              className={"dropdown-header"}
              onClick={() => setOpen(!open)}
              // ref={menuRef1}
            >
              {!open ? (
                <div className={selected ? "title-active " : "dropdown-title"}>
                  {selected ? selected : "dropdown-select"}
                </div>
              ) : (
                <div className={selected ? "active-color " : "dropdown-title"}>
                  {selected ? selected : "dropdown-select"}
                </div>
              )}
              <i
                className={open ? "fas fa-chevron-up" : "fas fa-chevron-down"}
              ></i>
            </div>
            {open ? (
              <div
                className={selected ? "active-label active-label--up" : "label"}
              >
                {open ? "Hint Text" : "Title"}{" "}
              </div>
            ) : (
              <div className={selected ? "active-label " : "label "}>
                {open ? "Hint Text" : "Title"}{" "}
              </div>
            )}
          </div>
          {open && (
            <ul className="list">
              {options.map((option, i) => (
                <li
                  onClick={() => {
                    setSelected(option);
                    setOpen(false);
                  }}
                  className="list-item"
                  tabIndex="0"
                >
                  {option}
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>
    </div>
  );
};

export default Dropdown;

这是输出

enter image description here

我想使用向上和向下箭头键在选项之间移动...尝试了很多解决方案但不起作用

我使用数组作为选项列表并通过它进行映射并显示在下拉列表中。 一切工作正常,但只是不知道如何将键盘按键映射到选项列表

最佳答案

您可以为每个选项创建一个引用数组

const optionRefs = useRef(options.map(() => createRef()));

然后使用这些引用

options.map((option, index) => (<li ... ref={optionRefs.current[index]} >...</li>)

然后在导航时将焦点更改为引用... 就像将第一个焦点放在向下箭头上一样:

optionRefs.current[0].current?.focus();

关于javascript - 如何在 react 中使用向上和向下箭头键使下拉菜单工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70155232/

相关文章:

javascript - 使用 mithril.js 和 jsx 构建一些 UI

javascript - d3力布局中心节点定位

reactjs - 根据条件渲染其中一个 child

javascript - 为什么嵌套数组对象在 react 组件中不起作用

c# - 在 Internet Explorer 中使用 javascript 和 XPATH 获取元素

javascript - Jquery定时器滑动功能

arrays - 有没有办法在 React 中执行 array.join

javascript - react : store array objects in state and display with keys

reactjs - 期望 SWR 库返回缓存数据但没有发生

javascript - 如何使用 firebase cloud firestore 为复选框保留多个数据?