码迷,mamicode.com
首页 > 其他好文 > 详细

react路由

时间:2019-11-13 16:19:14      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:out   nbsp   component   组件   跳转   view   route   one   div   

先下载路由

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组件

 

 

 

react路由

标签:out   nbsp   component   组件   跳转   view   route   one   div   

原文地址:https://www.cnblogs.com/dropInInt/p/11849737.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!