基础组件(Basic Components)
React Router中有三种类型的组件:路由组件(router components),路由匹配组件(route matching components)和导航组件(navigation components.)。在Web应用程序中使用的所有组件都应从react-router-dom导入。即
import { BrowserRouter, Route, Link } from "react-router-dom";
1. Routers(路由方式)
每个React Router应用程序的核心部分都应该是路由组件(router components)。 对于Web项目来说,react-router-dom提供了<BrowserRouter>
和<HashRouter>
两种router。 这两种路由方式都会创建一个专门的history 对象。 一般来说,如果有一个能够进行动态的数据请求的服务器,则应使用<BrowserRouter>
;否则,如果使用静态数据,则应使用<HashRouter>
。
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
holder
);
2. Route Matching(路由匹配)
有两种路由匹配组件<Route>
和<Switch>
。
import { Route, Switch } from "react-router-dom";
Route Matching是通过将<Route>
的path
属性与当前地址的pathname
属性进行比较来完成的。 当<Route>
的path
属性与当前地址的pathname
属性匹配时,<Route>
中的components
属性中指定组件就会被渲染出来。反之则不会被渲染。当<Route>
不指定path
属性的话则总是被渲染。
// when location = { pathname: '/about' }当前地址的pathname是/about时
<Route path='/about' component={About}/> // renders <About/>//如果path属性也为'/about',组件About将被渲染
<Route path='/contact' component={Contact}/> // renders null//如果path属性不为'/about',组件Contact不会被渲染,render为空
<Route component={Always}/> // renders <Always/>/如果不设置path属性,组件Always始终被渲染
可以将<Route>
放置在任何的容器之中。 此外罗列<Route>
通常是很有意义的。 可以用<Switch>
组件将<Route>
罗列在一起。
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
如果我们要罗列<Route>
,<Switch>
并不是必须的,但它可能非常有用。 <Switch>
将遍历其所有的<Route>
元素,并仅渲染与当前地址怕匹配的第一个子元素。 这在以下情况将很有帮助:
- 当前地址同多个
<Route>
的path
属性匹配 - 路由是排他的(即exact属性为true)
- 没有匹配到任何一个Route。(在这种情况下,可以渲染“404”组件)
<Switch>
<Route exact path="/" component={Home} /> //
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
{/*当以上地址都不匹配时, <NoMatch>将被渲染 */}
<Route component={NoMatch} />
</Switch>
3. Route Rendering Props(路由渲染属性)
对于给定的<Route>
组件有三个属性进行渲染component,render和children。
您可以查看<Route>
文档来获取每个的详细信息,但在这里我们将重点关注component,render
,因为这两种属性会经常用到。
component
渲染一个已经存在的组件,包括React组件或者是无状态函数组件。render
其应当传递一个函数,只有当你必须将局部变量传递给要渲染的组件时才使用。 不应该在component
属性中用函数来传递局部变量,这会导致不必要的组件装载/卸载。
const Home = () => <div>Home</div>;
const App = () => {
const someVariable = true;
return (
<Switch>
{/*应当这样做*/}
<Route exact path="/" component={Home} />
<Route path="/about" render={props => <About {...props} extra={someVariable} />} />
{/*不要这样做 */}
<Route path="/contact" component={props => <Contact {...props} extra={someVariable} />}/>
</Switch>
);
};
4. Navigation(导航)
React Router 提供了组件用于在应用中创建链接(links)。组件会渲染成HTML中的锚文本()。
application’s HTML.<Link to="/">Home</Link>
// <a href='/'>Home</a>
<NavLink>
是一种特殊类型的<Link>
组件。当他的to
属性中指定的位置与当前位置匹配时,组件样式将会设置成“active”样式。
// location = { pathname: '/react' }
<NavLink to="/react" activeClassName="hurray">React</NavLink>
// 等价于<a href='/react' className='hurray'>React</a>
你可以使用<Redirect>
组件来强制跳转。<Redirect>
会强制跳转到to
属性上指定的位置。