React-Router 的安装
npm install react-router
React-Router提供了两个组件:Router和Route。下面看最简单的例子:
src/Routes.js
1 import React from 'react' 2 import {Router,Route,browserHistory} from 'react-router' 3 4 import Home from './pages/Home.js' 5 import About from './pages/About.js' 6 import NotFound from './pages/NotFound.js' 7 8 const history = browserHistory; 9 const Routes = () =>( 10 <Router history = {browserHistory}> 11 <Route path = "home" component = {home}> 12 <Route path = "about" component = {About}> 13 <Route path = "*" component = {NotFound}> 14 </Router > 15 ); 16 export default Routes;
Routes.js文件返回一个组件,该组件输出一个Router组件实例,路由及其规则都封装在里面,Route组件内的path和component把路径和组件对应起来。
路由链接:
HTML的链接被点击时会发生默认跳转,这不符合单页面应用的要求,所以React-Router提供了一个<Link>组件来支持路由链接。
1.<link>组件产生html链接。
2.对该链接的点击不会引发跳转,而是把目标路径发送给Router,让Router依据关联显示对应的组件。
3.<Link>组件的to指向一个路径,对应的路径在Router中应该有定义。
1 import React from 'react' 2 import {Link} from 'react-router' 3 4 const view = ()=>{ 5 <div> 6 <ul> 7 <li><Link to="/home">Home</Link></li> 8 <li><Link to="/about">About</Link></li> 9 </ul> 10 </div> 11 };
嵌套:
Route提供了嵌套功能。路由的嵌套和组件层级的显示是对应的。当我们触发了子路由的跳转时,父层路由显示的东西可以依然保留在页面上,只有子层路由对应的组件发生变更。
比如在src/pages/App.js中定义组件App:
1 import React from 'react' 2 import {view as TopMenu} from '../components/TopMenu' 3 4 const App = ({children}) =>{ 5 return ( 6 <div> 7 <TopMenu /> 8 <div>{children}</div> 9 </div> 10 ) 11 } 12 export default App
上面代码中children是App的子组件。这是React中原生的特性。
React-Router中路由嵌套需要组件和Route的双边设置:
在组件中将children获得的子组件在恰当位置渲染;
在Route中 ,则是设置嵌套的<Route>
1 const Routes = ()=>( 2 <Router history = {browserHistory}> 3 <Route path = "/" component = {App}> 4 <Route path = "hone" component={home} /> 5 <Route path = "hone" component={home} /> 6 <Route path = "hone" component={home} /> 7 </Route> 8 </Route> 9 );