目录
之前的文章中,已经介绍过了 BrowserRouter / HashRouter,Route,Switch,withRouter 这些组件。
再介绍3个常用的组件:
1,Link
生成一个无刷新跳转的 <a> 元素。
主要的属性:
to- 字符串,表示跳转的路径
- 对象,属性和
history.location的属性相同。
replace,表示跳转时是否替换当前地址,默认false。innerRef,可以将 Link 内部的<a>元素的ref附着到传递的对象或函数上。
无刷新跳转的大致原理:
js
import { withRouter } from "react-router-dom";
function Link(props) {
return (
<a
href={props.to}
onClick={(e) => {
e.preventDefault();
props.replace ? props.history.replace(props.to) : props.history.push(props.to);
}}
>
{props.children}
</a>
);
}
export default withRouter(Link);
node 就是 a 元素。
innerRef={node => { console.log(node)}}
2,NavLink
在 Link 的基础上实现的,并添加了额外的功能:
当 to 匹配到当前路径时,会对生成的 <a> 元素添加对应的类名或样式,来表示激活状态。
举例:
html
<NavLink to="/b">跳转b</NavLink>
如果当前的路由路径是匹配到 /b 的(/b、/b/c 等),则 <NavLink> 会给对应的 <a> 元素添加 class="active",这样就可以设置激活状态的 <a> 元素的样式了。
生成的 <a> 元素
html
<a aria-current="page" class="active" href="/b">跳转b</a>
主要的属性:
activeClassName,匹配时的类名,默认active。activeStyle,匹配时的样式,可以直接写内联样式。exact,sensitive和Route组件对应的属性的含义一致。
3,Redirect
重定向组件,当加载到该组件时,会自动无刷新的跳转到指定的地址。
举例1 :除了 /a 或 /b,其他任何路径都会重定向到 /a:
html
<Router>
<Switch>
<Route path="/a" component={A}></Route>
<Route path="/b" component={B}></Route>
<Redirect to="/a">重定向到 /a</Redirect>
</Switch>
</Router>
举例2 :当访问根路径时,登录状态则重定向到 /dashboard,否则渲染 <PublicHomePage /> 组件
html
<Route exact path="/">
{loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>
主要的属性:
to,表示要重定向的路径。字符串或对象,和<Link>的to属性一样。push,表示重定向跳转是push|repalce,默认false。from,表示匹配到from对应的路径规则,才会进行跳转到to。exact,是否精确匹配from。sensitive,匹配from时是否对大小写敏感。
to和from都可以写正则表达式,和<Route path="/a/:id">一样。
举例3:
html
<Redirect from="/c/:id" to="/a">重定向到 /a</Redirect>
当匹配到 /c/xxx 时,才会跳转到 /a
举例4:
html
<Redirect from="/c/:id" to="/a/:id">重定向到 /a</Redirect>
当匹配到 /c/xxx 时,会跳转到 /a/xxx。
以上。