有没有办法让侧边栏与右侧内容一起保留,并且在 React Router v6 中仍然具有嵌套路由?

问题描述 投票:0回答:1

我想要一个侧边栏,右侧有一些卡片。当我单击卡片时,我想导航到名为 Note 的组件,但左侧仍然有侧边栏。

我遵循了这个https://reactrouter.com/en/main/start/tutorial,但他们没有右侧的内容,所以它可以工作。我试着到处找它但找不到。

非常感谢您的帮助。

这是迄今为止我的路由器(应用程序有侧边栏和卡片):

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    children: [
      {
        path: "notes/:id",
        element: <Note />,
      },
    ],
  },
]);
javascript reactjs react-router react-router-component
1个回答
0
投票
 In React Router v6, you can achieve a layout with a fixed sidebar and 
dynamic content on the right side, even when navigating to nested routes.

import { Outlet } from 'react-router-dom';
import Sidebar from './Sidebar';
import Cards from './Cards';

const App = () => {
  return (
    <div style={{ display: 'flex' }}>
      <Sidebar />
      <Cards />
      <div style={{ flex: 1, marginLeft: '250px' }}>
        {/* Outlet renders the matched child route component */}
        <Outlet />
      </div>
    </div>
  );
};

export default App;

在此示例中,Sidebar 和 Cards 组件渲染在左侧,Outlet 组件在右侧渲染匹配的子路由组件。右侧容器上的 flex: 1 样式确保它占用剩余空间,将内容推到右侧。 现在,您的路由器配置可能如下所示:

const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      {
        index: true,
        element: <div>Home Page</div>,
      },
      {
        path: 'notes/:id',
        element: <Note />,
      },
    ],
  },
]);
© www.soinside.com 2019 - 2024. All rights reserved.