本文主要记录react项目react-router的使用,主要介绍两种,Link 和 NavLink
//menuList.js 导航条
import { NavLink ,Link} from 'react-router-dom'
<NavLink exact to={childItem.path} data-index={number} className= {store.childNowIndex === number ? 'selectItem' : ''}>{childItem.title}
</NavLink>
//routeConfig.js
import { Route } from 'react-router-dom'
<Route exact path="/" component={Login} />
1、Link
当 你点击<Link>时,url会更新,组件会被重新渲染,但是页面不会重新加载,to可以是字符串也可以是对象,to={{pathname: '/courses',search: '?sort=name',hash: '#the-hash',state: { fromDashboard: true }}
// to为string
<Link to="/about">关于</Link>
// to为obj
<Link to={{
pathname: '/courses',
search: '?sort=name',
hash: '#the-hash',
state: { fromDashboard: true }
}}/>
// replace
<Link to="/courses" replace />
2、NaviLink
NavLink
<NavLink>是<Link>的一个特定版本,会在匹配上当前的url的时候给已经渲染的元素添加参数,组件的属性有
activeClassName(string):设置选中样式,默认值为active
activeStyle(object):当元素被选中时,为此元素添加样式
exact(bool):为true时,只有当导致和完全匹配class和style才会应用
strict(bool):为true时,在确定为位置是否与当前URL匹配时,将考虑位置pathname后的斜线
isActive(func)判断链接是否激活的额外逻辑的功能
嗯、看例子就懂了
// activeClassName选中时样式为selected
<NavLink
to="/faq"
activeClassName="selected"
>FAQs</NavLink>
// 选中时样式为activeStyle的样式设置
<NavLink
to="/faq"
activeStyle={{
fontWeight: 'bold',
color: 'red'
}}
>FAQs</NavLink>
// 当event id为奇数的时候,激活链接
const oddEvent = (match, location) => {
if (!match) {
return false
}
const eventID = parseInt(match.params.eventID)
return !isNaN(eventID) && eventID % 2 === 1
}
<NavLink
to="/events/123"
isActive={oddEvent}
>Event 123</NavLink>