简体   繁体   English

如何在反应中使用向上和向下箭头键使下拉菜单工作

[英]how to make dropdown work using up and down arrow keys in react

i am trying to make a custom dropdown using react where it should work with keyboard up and down keys also我正在尝试使用 react 来制作自定义下拉菜单,它也应该与键盘上下键一起使用

this is what i tried so far这是我到目前为止尝试过的

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;

here is the output这是 output

在此处输入图像描述

i want to move between options using up and down arrow key... tried many solutions but not working我想使用向上和向下箭头键在选项之间移动...尝试了很多解决方案但不起作用

i am using array as option list and mapping through it and displaying in dropdown.我使用数组作为选项列表并通过它映射并显示在下拉列表中。 everything is working fine but just dont know how to map keyboard keys to option list一切正常,但只是不知道如何 map 键盘键到选项列表

You can create an Array of refs for each option您可以为每个选项创建一个引用数组

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

then use the these refs然后使用这些参考

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

and then change the focus to the ref when you navigate... like focussing the first on down arrow:然后在导航时将焦点更改为 ref ......就像将第一个焦点放在向下箭头上:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM