@H_
301_0@
不太熟悉react路由器,但我需要NavLink的
功能来设置父li元素的活动类,而不是a元素.
为了实现这一点,我只看了NavLink的源代码并将其复制到一个新元素. (使用打字稿的示例,但与js大致相同)
import * as React from 'react';
import { Link,withRouter,Route } from 'react-router-dom';
class LiNavLink extends React.Component<any,{}> {
render() {
const {to,exact,strict,activeClassName,className,activeStyle,style,isActive: getIsActive,...rest } = this.props;
return (
<Route
path={typeof to === 'object' ? to.pathname : to}
exact={exact}
strict={strict}
children={({ location,match }) => {
const isActive = !!(getIsActive ? getIsActive(match,location) : match)
return (
<li
className={isActive ? [activeClassName,className].join(' ') : className}
style={isActive ? { ...style,...activeStyle } : style}>
<Link
to={to}
{...rest}
/>
</li>
)
}}
/>
);
}
}
export default LiNavLink;
然后用法:
<ul>
<LiNavLink activeClassName='active' exact={true} strict to="/example"><span>Active</span></LiNavLink>
<LiNavLink activeClassName='active' exact={true} strict to="/example/archived"><span>Archived</span></LiNavLink>
</ul>
我正在使用HashRouter,由于某些我无法弄清楚的原因,当路由发生变化时,这不会更新,只有当我“刷新”页面时才更新它应该如何更新.
我相信它永远不会更新,因为道具永远不会改变?所以它不知道更新自己?
我该如何更新?或者我的问题在别的地方?
我刚刚开始做出反应,所以不确定这是不是最好的做法,但在通过路由器v4文档后,我使用了路由器道具 – > location.pathname并将其与我的路线进行比较.
这是Navigation.js:
import React from 'react';
import { withRouter } from 'react-router-dom';
import NavLink from '../General/NavLink';
const activeClass = (path,link) => {
if (path === link) {
return true;
}
return false;
};
const Navigation = props => {
const { location } = props;
return (
<ul className="menu menu--main nano-content">
<NavLink
to="/"
parentClass={
activeClass(location.pathname,'/')
? 'menu__item menu__item--active'
: 'menu__item'
}
linkClass="menu__link effect effect--waves"
>
Dashboard
</NavLink>
<NavLink
to="/users"
parentClass={
activeClass(location.pathname,'/users')
? 'menu__item menu__item--active'
: 'menu__item'
}
linkClass="menu__link effect effect--waves"
>
Users
</NavLink>
<NavLink
to="/projects"
parentClass={
activeClass(location.pathname,'/projects')
? 'menu__item menu__item--active'
: 'menu__item'
}
linkClass="menu__link effect effect--waves"
>
Projects
</NavLink>
<NavLink
href="http://google.com"
parentClass="menu__item"
linkClass="menu__link effect effect--waves"
>
Google
</NavLink>
</ul>
);
};
export default withRouter(Navigation);
从那里你可以在子组件上使用父类和子类.