先下载路由
1 npm install react-router-dom --save-dev
然后新建两个页面
component1.js
1 import React from 'react'; 2 3 class Component1 extends React.Component{ 4 render(){ 5 return ( 6 <div> 7 <a href="#/component2">去component2</a> 8 </div> 9 ); 10 } 11 } 12 13 export default Component1
component2.js
import React from 'react'; class Component2 extends React.Component{ render(){ return ( <div> <a href="/">回到component1</a> </div> ); } } export default Component2
注意:React.Component的Component中C一定要大写
然后新建Routers.js
1 import React from 'react'; 2 import {HashRouter, Route, Switch} from 'react-router-dom'; 3 import Component1 from '../view/Component1'; 4 import Component2 from '../view/Component2'; 5 6 const BasicRoute = () =>( 7 <HashRouter> 8 <Switch> 9 <Route exact path='/' component={Component1}/> 10 <Route exact path='/component2' component={Component2}/> 11 </Switch> 12 </HashRouter> 13 ) 14 15 export default BasicRoute;
在index.js中编写如下:
1 import React from 'react'; 2 import ReactDOM from 'react-dom'; 3 import Router from './router/Routers' 4 5 ReactDOM.render(<Router />, document.getElementById('root'));
这样完成了一个简单的路由跳转
路由的exact属性
具体区别如下:
1 <Route path='/' component={Home} /> 2 <Route path='/page' component={Page}> 3 //这种情况下,如果匹配路由path='/page',那么会把Home也会展示出来。 4 //既路由path='/page'会匹配路由path='/'和路由path='/page'
1 <Route exact path='/' component={Home} /> 2 <Route path='/page' component={Page} /> 3 //这样匹配路由path='/page',只会匹配到Page组件