React Router 基础组件一览

在 React Router 中有三种类型的组件:路由器组件,路由匹配组件,导航组件。这些组件都来自于 react-router-dom

路由器

对于每一个 React Router 应用来说,都应该有一个路由器组件,它们会为应用创建一个专用的 history 对象。针对 Web 项目,react-router-dom 提供了 <BrowserRouter><HashRouter>

import { BrowserRouter } from 'react-router-dom';

ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>
), holder);

具体使用方式参见 BrowserRouterHashRouter

路由

React Router 提供了两种路由匹配组件:<Route><Switch>

Route 组件

路由匹配是通过比较 <Route> 组件的 path 属性和当前地址的 pathname 实现的,如果匹配则渲染当前路由组件的内容,如果不匹配则渲染 null。注意:没有提供 path 属性的 <Route> 组件将总是匹配。

import { Route } from 'react-router-dom';

// when location = { pathname: '/about' }
<Route path='/about' component={About} /> // renders <About/>
<Route path='/contact' component={Contact} /> // renders null
<Route component={Always} /> // renders <Always/>

具体使用方式参见 Route

Switch 组件

<Switch> 组件用于给 <Route> 组件分组,可以将一组 <Route> 组件嵌套在 <Switch> 组件中。

那么,<Switch> 组件仅是为了给 <Route> 组件分组而诞生的吗?我们知道 <Route> 组件通过比较它的 path 属性和当前地址来判断是否渲染它的内容,所以就会存在多个 <Route> 匹配成功且都渲染它们内容的情况。为了避免这样的情况,<Switch> 组件就起了作用,它会迭代当中的 <Route> 组件,并选出第一个匹配的 <Route> 来渲染。

import { Switch, Route } from 'react-router-dom';

<Switch>
  <Route exact path='/' component={Home} />
  <Route path='/about' component={About} />
  <Route path='/contact' component={Contact} />
  {/* when none of the above match, <NoMatch> will be rendered */}
  <Route component={NoMatch} />
</Switch>

具体使用方式参见 Switch

导航

React Router 提供了 <Link> 组件用于为应用提供链接,当渲染 <Link> 组件的时候,会在应用中渲染为 HTML 的 <a> 标签。

另外还有一个特殊的 <Link> 组件就是 <NavLink>,如果当前的地址与它的属性相匹配,它就会使用 "active" 样式。

任何时候如果您想要强制一个导航,就可以使用 <Redirect> 组件,当它被渲染的时候,就会导航到它的属性。

<Link to='/'>Home</Link>
// <a href='/'>Home</a>

// location = { pathname: '/react' }
<NavLink to='/react' activeClassName='hurray'>React</NavLink>
// <a href='/react' className='hurray'>React</a>

<Redirect to='/login'/>

具体使用方式参见 LinkNavLinkRedirect