通过箭头键导航路由器

Navigating Router Through Arrow Keys

正如标题所说,我实际上是在尝试通过在循环列表中使用左右箭头键来浏览我的网页。每次按下右箭头,导航栏 select 向右移动下一个元素,每次按下左箭头,导航栏 select 向左移动页面。

我已经创建了一个功能来检测左右箭头按键,但截至目前它只是 console.logs,我对路由器和交换机不是很熟悉,所以我正在尝试开发一些功能来更改使用箭头键操作导航栏(同时保持 select 的能力)

import "./App.css";
import { useRef } from "react";
import { useEffect } from "react";
import Navigation from "./Components/UI/Navigation";
import CentralReport from "./Components/Central Report/CentralReport";
import ImageSlideShow from "./Components/Slideshow/ImageSlideShow";
import MapSlideShow from "./Components/Slideshow/MapSlideShow";
import { BrowserRouter as Switch, Route } from "react-router-dom";

function useKey(key, cb) {
  const callbackRef = useRef(cb);

  useEffect(() => {
    callbackRef.current = cb;
  });
  useEffect(() => {
    function handle(event) {
      if (event.code === key) {
        callbackRef.current(event);
      }
    }
    document.addEventListener("keydown", handle);
    return () => document.removeEventListener("keydown", handle);
  }, [key]);
}

function App() {
  function handleArrowLeft() {
    console.log("Left");
  }
  function handleArrowRight() {
    console.log("Right");
  }
  useKey("ArrowLeft", handleArrowLeft);
  useKey("ArrowRight", handleArrowRight);

  return (
    <div>

      <Switch>
        <Route exact path="/central-report" component={CentralReport} />
        <Route path="/images" component={ImageSlideShow} />
        <Route path="/maps" component={MapSlideShow} />
      </Switch>

      {/* NavBar */}
      <Navigation />
    </div>
  );
}

export default App;

您可以简单地通过添加路径数组来做到这一点,并使用历史推送来重定向,并获取当前索引的位置:

  useEffect(() => {
    const currentIndex = paths.indexOf(location.pathname);
    if (currentIndex === 0) {
      setPrevRoute(paths.length - 1);
    } else {
      setPrevRoute(currentIndex - 1);
    }

    if (currentIndex === paths.length - 1) {
      setNextRoute(0);
    } else {
      setNextRoute(currentIndex + 1);
    }
  }, [location.pathname]);

  function handleArrowLeft() {
    history.push(paths[prevRoute]);
  }

  function handleArrowRight() {
    history.push(paths[nextRoute]);
  }

Demo Base on your code

因为你使用的是功能组件,所以钩子是首选。下面应该让你上路,你只需要添加一些逻辑来决定应该将什么路径推送到历史数组。

import { useHistory } from 'react-router-dom'

function App() {
  const history = useHistory()

  function handleArrowLeft() {
    console.log("Left");
    history.push("/path-to-the-left")
  }
  function handleArrowRight() {
    console.log("Right");
    history.push("/path-to-the-right")
  }
  useKey("ArrowLeft", handleArrowLeft);
  useKey("ArrowRight", handleArrowRight);

  return (
    <div>

      <Switch>
        <Route exact path="/central-report" component={CentralReport} />
        <Route path="/images" component={ImageSlideShow} />
        <Route path="/maps" component={MapSlideShow} />
      </Switch>

      {/* NavBar */}
      <Navigation />
    </div>
  );
}