我在教育项目中使用Reactstrap和React-router 4.0.0-beta.6,它位于带有自定义域的gitlab上。
根据Reactstrap文档:我应该使用主动 navlink
import { NavLink } from 'reactstrap'
...
<NavLink href="#" active = true >Link< /NavLink>
根据React-router v4 docs:
import { NavLink } from 'react-router-dom'
...
<NavLink to="/about" activeClassName="active">About</NavLink>
那么我应该如何实现navlink活动状态并使用react-router?
答案 0 :(得分:11)
要同时使用这两种导入,您需要重命名其中一个导入并在reactstrap NavLink中使用标记prop。您将无法在reactstrap NavLink上使用活动prop,因为该逻辑存在于反应路由器NavLink中。
这是它应该是什么样子:
import { NavLink } from 'reactstrap';
import { NavLink as RRNavLink } from 'react-router-dom';
<NavLink to="/about" activeClassName="active" tag={RRNavLink}>About</NavLink>
答案 1 :(得分:3)
默认情况下使用he path: 256
Program end
with exit code: 0
类。您只需使用active
布尔属性来匹配确切的路径。
exact
查看 react-router.NavLink 组件的源代码:https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/NavLink.js
答案 2 :(得分:1)
我的建议是在使用React Router v4和Reactstrap(Bootstrap)时避免<Link>
,<NavLink>
和tag
。我真的认为应该弃用这三个,尤其是tag
属性。尝试将React Router的<Link>
和<NavLink>
混合到Reactstrap组件中会导致Bootstrap无法预料的样式问题(例如:https://github.com/reactstrap/reactstrap/issues/562)。
我发现从风格的角度来看,最好使用React Router v4 <Route>
组件,并将history
道具传递给Reactstrap组件。
import { Route } from 'react-router-dom';
import { Button } from 'reactstrap';
<Route
render={props =>
<Button role="button"
onClick={() => props.history.push("/endpoint")}>
</Button>}
/>
答案 3 :(得分:1)
由于您使用reactstrap来处理导航栏的样式,因此您不需要依赖来自react-router的NavLink来执行相同的操作。
您可以使用来自react-router的链接,它仅处理路由,并且不会添加“活动”。选择时的className。但那没关系,因为bootstrap的NavLink会为你做样式。
import { NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';
<NavLink><Link to="/about">About</Link></NavLink>
答案 4 :(得分:0)
我使用这样的东西:
<NavLink to="/about" active={window.location.hash === '/about'}>About</NavLink>
答案 5 :(得分:0)
我有exact prop in react-router 4.3.1 route
,但还需要添加exact to reactstrap 7.0.2 NavLink
,以防止基本路线在所有其他子路线上都显示为活动路线。
import { Link, NavLink as RRNavLink, withRouter } from "react-router-dom";
import { NavItem, NavLink } from "reactstrap";
<NavItem>
<NavLink to="/" activeClassName="active" exact tag={RRNavLink}>
Home
</NavLink>
</NavItem>
<NavItem>
<NavLink to="/some-route" activeClassName="active" tag={RRNavLink}>
Some Text
</NavLink>
</NavItem>