【问题标题】:How do I use multiple navbars in my react application如何在我的 React 应用程序中使用多个导航栏
【发布时间】:2023-01-16 22:41:32
【问题描述】:

我想有一个不同的导航栏对于我网站上的每条路径,我都想出了一个办法,但它并没有真正改变直到我刷新页面这显然不是我想要的。 (我正在使用反应路由器 v6。3个)

    function Navbar() {
if (window.location.pathname === "/") {
return (
<nav style={{ backgroundColor: "rgb(17, 105, 142)" }}>...</nav>
);
} else if (window.location.pathname === "/products") {
return (
<nav className="products-nav">...</nav>
);
} else if (window.location.pathname === "/addproducts") {
return (
<nav className="addproducts-nav">...</nav>
);
} else ...

Here的完整代码以防万一

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    您可以使用 react-router-dom 中的 useLocation 挂钩,它返回当前位置对象 https://reactrouter.com/en/main/hooks/use-location

    【讨论】:

      【解决方案2】:

      如果您使用的是 React 路由器,则不应再直接使用 window.location。使用反应路由器提供的值。 window.location 更改不会触发重新渲染,这就是您看不到更改的原因。

      等效的 React 路由器是使用 useLocation 钩子

      【讨论】:

      • 具体是什么道具?
      • 该位置可通过 useLocation 挂钩从 react-router 的上下文中获得
      猜你喜欢
      • 2016-07-29
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      相关资源
      最近更新 更多