简体   繁体   English

React-router v5.2 NavLink 活动未按预期工作

[英]React-router v5.2 NavLink active not working as expected

I have routes like "/works/:type/:id".我有像“/works/:type/:id”这样的路线。 Shouldn't strict match all "/works/whatever/whatever" paths as the last two paths are dynamic values.不应严格匹配所有“/works/whatever/whatever”路径,因为最后两个路径是动态值。 But this is not the case.但这种情况并非如此。 I am trying to enforce with isActive as well but no luck with that either.我也在尝试使用 isActive 强制执行,但也没有运气。 Once ON always ON behaviour kicks in as no reloading happens, Even though with "useEffect" hook, we can detect the URL change and update the isActive correctly.一旦 ON always ON 行为开始,因为没有重新加载发生,即使使用“useEffect”钩子,我们也可以检测到 URL 更改并正确更新 isActive。 once ON always ON.一次开总是开。 Can someone put me in the right direction please how to handle this.有人可以让我朝着正确的方向前进,请问如何处理。

`<NavLink
     className="nav-link"
     activeStyle={{ color: "#f5d62d" }}
     isActive={() => isWorks}
     to="/works/moving-image/intro"
 />
                                                                                                    

` `

Well I hope this helps someone one day;-) This is all achieved with useEffect and withRouter from react-router.好吧,我希望有一天这对某人有所帮助;-) 这一切都是通过 react-router 的 useEffect 和 withRouter 实现的。

import { withRouter, NavLink } from "react-router-dom";

export default withRouter(function SomeFuntionComponent({ location }) {
  const [currentPath, setCurrentPath] = useState(location.pathname);

  useEffect(() => {
    const { pathname } = location;
    console.log("New path:", pathname);
    setCurrentPath(pathname);
  }, [location.pathname]);

Then finally add isActive on your NavLink as below然后最后在您的 NavLink 上添加 isActive 如下

isActive={() => (currentPath.indexOf("/some-link") > -1)}
      

<NavLink
            strict
            className="nav-link"
            isActive={() => (currentPath.indexOf("/moving") > -1)}
            activeStyle={{ color: "white" }}
            to="/some-link"
          >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM