You need to enable JavaScript to run this app. React开发页点击侧边栏跳转后侧边栏消失的解决方案求助
优惠活动
大模型
产品
解决方案
定价
更多

React开发页点击侧边栏跳转后侧边栏消失的解决方案求助

解决方案:嵌套路由 + 状态同步 + Context 避免Props Drilling

核心思路

要实现侧边栏常驻、子页面切换且URL同步的效果,核心是用React Router嵌套路由让侧边栏所在的父组件始终挂载,子页面通过Outlet渲染在父组件的内容区域;同时通过路由参数同步侧边栏选中状态,用React Context处理跨组件共享状态,彻底避免props drilling。


步骤1:调整路由结构(App.js)

将/development设为父路由,子路由(首页、带:id的子页面)嵌套在其中,父路由渲染带侧边栏的DevelopmentPage,子路由内容通过Outlet渲染在侧边栏右侧。

import { Routes, Route } from 'react-router-dom';
import DevelopmentPage from './DevelopmentPage';
import ChildPage from './ChildPage';

function App() {
  return (
    <Routes>
      {/* 其他业务路由 */}
      <Route path="/development" element={<DevelopmentPage />}>
        {/* 默认首页:访问/development时渲染 */}
        <Route index element={<div>Development 首页内容</div>} />
        {/* 子页面:匹配/development/:id */}
        <Route path=":id" element={<ChildPage />} />
      </Route>
    </Routes>
  );
}

export default App;

步骤2:实现带侧边栏的父组件(DevelopmentPage.js)

在DevelopmentPage中渲染侧边栏,用useParams获取当前路由参数同步选中状态,点击侧边栏标签时通过useNavigate跳转路由,子页面内容通过Outlet渲染。

import { Outlet, useNavigate, useParams } from 'react-router-dom';
import { useSidebar } from './SidebarContext';

// 侧边栏标签数据
const sidebarItems = [
  { id: 'getting-started', label: '快速上手' },
  { id: 'core-concepts', label: '核心概念' },
  { id: 'advanced-guides', label: '进阶指南' },
];

function DevelopmentPage() {
  const navigate = useNavigate();
  const { id } = useParams();
  // 用路由参数同步选中状态,默认选中第一个标签
  const activeItemId = id || 'getting-started';
  // 若需要侧边栏展开/收起状态,用Context获取
  const { isCollapsed, setIsCollapsed } = useSidebar();

  // 点击侧边栏标签跳转路由
  const handleItemClick = (itemId) => {
    navigate(itemId);
  };

  return (
    <div style={{ display: 'flex', height: '100vh' }}>
      {/* 侧边栏 */}
      <aside style={{
        width: isCollapsed ? '60px' : '220px',
        borderRight: '1px solid #e0e0e0',
        padding: '16px',
        transition: 'width 0.3s'
      }}>
        <button onClick={() => setIsCollapsed(!isCollapsed)}>
          {isCollapsed ? '展开' : '收起'}
        </button>
        {sidebarItems.map(item => (
          <div
            key={item.id}
            onClick={() => handleItemClick(item.id)}
            style={{
              padding: '8px',
              margin: '8px 0',
              cursor: 'pointer',
              borderRadius: '4px',
              backgroundColor: activeItemId === item.id ? '#e3f2fd' : 'transparent',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap'
            }}
          >
            {!isCollapsed && item.label}
          </div>
        ))}
      </aside>
      {/* 右侧内容区域:渲染子页面 */}
      <main style={{ flex: 1, padding: '24px', overflowY: 'auto' }}>
        <Outlet />
      </main>
    </div>
  );
}

export default DevelopmentPage;

步骤3:用Context避免Props Drilling(SidebarContext.js)

如果侧边栏有需要跨组件共享的状态(比如展开/收起),创建Context统一管理,子组件直接通过useSidebar钩子获取,无需层层传参。

import { createContext, useContext, useState } from 'react';

const SidebarContext = createContext();

// 提供状态的Provider组件
export function SidebarProvider({ children }) {
  const [isCollapsed, setIsCollapsed] = useState(false);

  return (
    <SidebarContext.Provider value={{ isCollapsed, setIsCollapsed }}>
      {children}
    </SidebarContext.Provider>
  );
}

// 自定义钩子,简化Context调用
export function useSidebar() {
  return useContext(SidebarContext);
}

然后在App.js中用SidebarProvider包裹路由,确保所有子组件能访问状态:

import { SidebarProvider } from './SidebarContext';

function App() {
  return (
    <SidebarProvider>
      <Routes>
        {/* 路由内容 */}
      </Routes>
    </SidebarProvider>
  );
}

步骤4:子页面实现(ChildPage.js)

子页面通过useParams获取路由参数,渲染对应内容,若需要侧边栏状态直接用useSidebar获取。

import { useParams } from 'react-router-dom';
import { useSidebar } from './SidebarContext';

function ChildPage() {
  const { id } = useParams();
  const { isCollapsed } = useSidebar();

  return (
    <div>
      <h2>{id.replace('-', ' ')} 页面</h2>
      {isCollapsed && <p>侧边栏已收起</p>}
      {/* 根据id渲染对应内容 */}
    </div>
  );
}

export default ChildPage;

关键优势

  1. 侧边栏常驻:嵌套路由让DevelopmentPage始终挂载,侧边栏不会随页面跳转消失。
  2. 路由与UI同步:通过useParams直接从URL获取选中状态,无需手动维护state,避免状态不一致。
  3. 无Props Drilling:用React Context管理共享状态,子组件直接调用钩子获取,无需层层传递props。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 21:53:12