17 React-router

效果

 点击About,切换到About组件的内容

 点击Home,就切换到Home组件的内容

 默认是渲染About组件标签

第一步,准备

①下载:npm install --save react-router-dom

  

   在package.json中可以看到我们下载的依赖中有 react-router

②使用到路由组件是,在入口JS(index.js)中我们需要 需要把APP组件放在 路由组件的标签中,让 router 管理整个应用

  

    这里使用 <BrowserRouter > ,我们也可以使用 <HashRouter>

第二步:拆分组件(区分路由组件和非路由组件)

  

  ①共三个组件,APP 组件  About 组件 Home组件,其中About组件和Home组件时路由组件

  ②路由组件我们放在 components 文件夹中,非路由组件我们放在 pages 文件夹中

第三步:使用 react-router 库 实现路由组件

  ①首先路由链接 要使用 <NavLink> 标签,原来 a 标签中的 href 改为 to

    

    

   ②组件标签 使用 <Router > 标签

    

      

     但是界面上我们只能渲染一个组件标签,所以需要用到 <Switch> 标签,把路由组件标签放在 Switch 中,称为可切换的路由组件

    

   ③可以看到,路由组件已经实现成功了

    

    ④app.jsx

 1 import React, { Component } from 'react'
 2 import {Route,NavLink,Switch} from 'react-router-dom'
 3 
 4 import About from '../../pages/about/about'
 5 import Home from '../../pages/home/home'
 6 
 7 export default class App extends Component {
 8     render() {
 9         return (
10             <div>
11                 <div className="container">
12                     <div className="row">
13                         <h1>React Router Demo</h1>
14                     </div>
15                     <hr/>
16                     <div className="row">
17                         <div className="col-md-2">
18                             <div className="list-group">
19                                 <NavLink className="list-group-item" to="/about">About</NavLink>
20                                 <NavLink className="list-group-item" to="/home">Home</NavLink>
21                             </div>
22                         </div>
23                         <div className="col-md-6 col-md-offset-1">
24                             <Switch>
25                                 <Route path="/about" component={About}/>
26                                 <Route path="/home" component={Home}/>
27                             </Switch>
28                         </div>
29                     </div>
30                 </div>
31             </div>
32         )
33     }
34 }

可以看到这里并没有设置默认路由,而最后的页面效果中却默认显示了About 组件???

设置默认路由的方式是使用 <Redirect >

猜你喜欢

转载自www.cnblogs.com/shanlu0000/p/12510767.html