You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过左右方向键实现React Router路由及导航栏循环切换

实现方向键切换导航的修改方案

1. 修正react-router-dom的导入错误

你现有代码里错误地把BrowserRouter别名成了Switch,首先修正导入,同时新增需要的路由钩子:

// 把原来错误的导入替换为以下内容
import { BrowserRouter as Router, Switch, Route, useHistory, useLocation, Redirect } from "react-router-dom";

2. 定义固定路由顺序数组

按照导航栏的实际排列顺序定义路由列表,用来控制左右切换的逻辑:

// 顺序和导航栏展示顺序保持一致即可
const ROUTE_LIST = ["/central-report", "/images", "/maps"];

3. 修改App组件的路由操作逻辑

在App组件内获取路由实例,修改左右按键的处理函数,实现循环切换效果:

function App() {
  const history = useHistory();
  const location = useLocation();

  // 获取当前路径对应的路由索引
  const getCurrentRouteIndex = () => {
    return ROUTE_LIST.findIndex(route => route === location.pathname);
  }

  function handleArrowLeft() {
    const currentIndex = getCurrentRouteIndex();
    // 计算上一个路由索引,负数时自动跳到最后一个实现循环
    const prevIndex = (currentIndex - 1 + ROUTE_LIST.length) % ROUTE_LIST.length;
    history.push(ROUTE_LIST[prevIndex]);
  }
  function handleArrowRight() {
    const currentIndex = getCurrentRouteIndex();
    // 计算下一个路由索引,超过长度时自动跳回第一个实现循环
    const nextIndex = (currentIndex + 1) % ROUTE_LIST.length;
    history.push(ROUTE_LIST[nextIndex]);
  }
  useKey("ArrowLeft", handleArrowLeft);
  useKey("ArrowRight", handleArrowRight);

  return (
    <div>
      <Switch>
        {/* 新增首页默认重定向,避免打开首页时索引匹配失败 */}
        <Redirect exact from="/" to="/central-report" />
        <Route exact path="/central-report" component={CentralReport} />
        <Route path="/images" component={ImageSlideShow} />
        <Route path="/maps" component={MapSlideShow} />
      </Switch>

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

4. 外层包裹Router实例

需要在App组件的外层包裹Router才能让路由钩子生效,一般在项目入口文件index.js中修改:

// index.js 示例
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Router>
    <App />
  </Router>
);

原有点击功能兼容说明

不需要修改导航栏的原有逻辑,只要你的Navigation组件用的是react-router-dom提供的NavLink/Link组件做跳转,会自动和按键跳转逻辑兼容,导航项的激活高亮可以直接用NavLink自带的activeClassName属性配置。

内容的提问来源于stack exchange,提问作者NightBeezy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:54:03