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

React + Tailwind 侧边导航栏添加路由实现页面跳转问题求助

没问题!在React里实现单页应用的路由跳转,最常用也最推荐的就是官方生态的react-router-dom库,我来一步步帮你把这个侧边导航栏的跳转功能加上:


1. 先安装路由依赖

首先在你的项目根目录下执行命令,安装react-router-dom:

npm install react-router-dom
# 如果你用yarn的话
yarn add react-router-dom

2. 配置路由根容器

打开你的项目入口文件(一般是index.js),用BrowserRouter包裹整个App组件,这样整个应用就能使用路由功能了:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

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

3. 更新菜单数据,添加路由路径

给你的Menus数组里每个菜单项加上对应的跳转路径,方便后续路由匹配:

const Menus = [
  { title: "Home", src: "0", path: "/" },
  { title: "Site1", src: "1", gap: true, path: "/site1" },
  { title: "Site2 ", src: "2", path: "/site2" },
  { title: "Site3", src: "3", path: "/site3" },
  { title: "Site4", src: "4", path: "/site4" }
];

4. 修改侧边栏组件,实现跳转逻辑

这里有两种常用的实现方式,你可以根据需求选择:

方式一:使用Link组件(推荐,声明式风格)

Link是react-router-dom提供的专门用于路由跳转的组件,点击不会刷新整个页面,完全符合React单页应用的特性。修改你的App组件如下:

import { useState } from "react";
import { Link, Routes, Route } from "react-router-dom";

const App = () => {
  const [open, setOpen] = useState(true);
  const Menus = [
    { title: "Home", src: "0", path: "/" },
    { title: "Site1", src: "1", gap: true, path: "/site1" },
    { title: "Site2 ", src: "2", path: "/site2" },
    { title: "Site3", src: "3", path: "/site3" },
    { title: "Site4", src: "4", path: "/site4" }
  ];

  return (
    <div className="flex">
      {/* 侧边导航栏 */}
      <div className={` ${ open ? "w-72" : "w-20 " } bg-gray-800 p-5 pt-8 sticky top-0 left-0 h-[930px] duration-300`} >
        <img 
          src="./src/assets/control.png" 
          className={`absolute cursor-pointer -right-3 top-9 w-7 border-dark-purple border-2 rounded-full ${!open && "rotate-180"}`} 
          onClick={() => setOpen(!open)} 
        />
        <div className="flex gap-x-4 items-center">
          <img src="./src/assets/logo.png" className={`cursor-pointer duration-500 ${ open && "rotate-[360deg]" }`} />
          <h1 className={`text-white origin-left font-medium text-xl duration-200 ${ !open && "scale-0" }`} > Site </h1>
        </div>
        <ul className="pt-6">
          {Menus.map((Menu, index) => (
            <li 
              key={index} 
              className={`flex rounded-MD p-2 cursor-pointer hover:bg-light-white text-gray-300 text-sm items-center gap-x-4 ${Menu.gap ? "mt-9" : "mt-2"} ${ index === 0 && "bg-light-white" } `}
            >
              {/* 用Link包裹菜单项内容,指定跳转路径 */}
              <Link to={Menu.path} className="flex items-center gap-x-4 w-full">
                <img src={`./src/assets/${Menu.src}.png`} />
                <span className={`${!open && "hidden"} origin-left duration-200`}> {Menu.title} </span>
              </Link>
            </li>
          ))}
        </ul>
      </div>

      {/* 页面内容展示区域 */}
      <div className="flex-1 p-5">
        <Routes>
          {/* 配置路由和对应的页面组件 */}
          <Route path="/" element={<HomePage />} />
          <Route path="/site1" element={<Site1Page />} />
          <Route path="/site2" element={<Site2Page />} />
          <Route path="/site3" element={<Site3Page />} />
          <Route path="/site4" element={<Site4Page />} />
        </Routes>
      </div>
    </div>
  )
}

// 示例页面组件,你可以根据实际需求编写具体内容
const HomePage = () => <h1 className="text-2xl font-bold">Home Page</h1>;
const Site1Page = () => <h1 className="text-2xl font-bold">Site1 Page</h1>;
const Site2Page = () => <h1 className="text-2xl font-bold">Site2 Page</h1>;
const Site3Page = () => <h1 className="text-2xl font-bold">Site3 Page</h1>;
const Site4Page = () => <h1 className="text-2xl font-bold">Site4 Page</h1>;

export default App;

方式二:使用useNavigate钩子(适合需要额外逻辑的场景)

如果你的菜单项点击时需要先执行一些自定义逻辑(比如验证、日志记录)再跳转,可以用useNavigate钩子:

import { useState, useNavigate } from "react";
import { Routes, Route } from "react-router-dom";

const App = () => {
  const [open, setOpen] = useState(true);
  const navigate = useNavigate(); // 初始化导航钩子

  const Menus = [
    { title: "Home", src: "0", path: "/" },
    { title: "Site1", src: "1", gap: true, path: "/site1" },
    { title: "Site2 ", src: "2", path: "/site2" },
    { title: "Site3", src: "3", path: "/site3" },
    { title: "Site4", src: "4", path: "/site4" }
  ];

  // 自定义跳转逻辑
  const handleMenuClick = (path) => {
    // 这里可以添加你需要的前置逻辑,比如:
    console.log(`准备跳转到${path}`);
    // 执行跳转
    navigate(path);
  };

  return (
    <div className="flex">
      {/* 侧边导航栏 */}
      <div className={` ${ open ? "w-72" : "w-20 " } bg-gray-800 p-5 pt-8 sticky top-0 left-0 h-[930px] duration-300`} >
        {/* 省略其他重复代码 */}
        <ul className="pt-6">
          {Menus.map((Menu, index) => (
            <li 
              key={index} 
              className={`flex rounded-MD p-2 cursor-pointer hover:bg-light-white text-gray-300 text-sm items-center gap-x-4 ${Menu.gap ? "mt-9" : "mt-2"} ${ index === 0 && "bg-light-white" } `}
              onClick={() => handleMenuClick(Menu.path)} // 绑定点击事件
            >
              <img src={`./src/assets/${Menu.src}.png`} />
              <span className={`${!open && "hidden"} origin-left duration-200`}> {Menu.title} </span>
            </li>
          ))}
        </ul>
      </div>

      {/* 页面内容区域和方式一一致 */}
      <div className="flex-1 p-5">
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/site1" element={<Site1Page />} />
          {/* 其他路由配置 */}
        </Routes>
      </div>
    </div>
  )
}

// 页面组件同上...

为什么不用原生a标签?

直接用<a href>会触发整个页面的刷新,而React是单页应用(SPA),使用react-router-dom的路由可以实现无刷新跳转,只更新页面需要变化的部分,不仅提升用户体验,还能保留应用的状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 19:12:49