我有像"/works/:type/:id“这样的路由。最后两个路径是动态值,所以不应该严格匹配所有“/works/ are /are”路径。但事实并非如此!我也在尝试用isActive来强制执行,但也没那么走运。一旦打开,总是打开行为,因为没有重新加载发生。即使使用"useEffect“钩子,我们也可以检测到URL的变化并正确地更新isActive,一次打开就永远打开。有没有人能把我带到正确的方向,请告诉我如何处理这件事。
`<NavLink
className="nav-link"
activeStyle={{ color: "#f5d62d" }}
isActive={() => isWorks}
to="/works/moving-image/intro"
/>`
发布于 2020-08-04 18:52:50
好吧,我希望有一天这能帮助到某个人;-)这一切都是通过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]);最后在NavLink上添加isActive,如下所示
isActive={() => (currentPath.indexOf("/some-link") > -1)}
<NavLink
strict
className="nav-link"
isActive={() => (currentPath.indexOf("/moving") > -1)}
activeStyle={{ color: "white" }}
to="/some-link"
>https://stackoverflow.com/questions/63193529
复制相似问题