React中路由的基本使用

如今咱们来搞一搞React中的路由吧,别问我为何这木喜欢用搞这个字,由于它比较深奥。css

注意下面咱们使用的是React-Router-DOMreact

React中的路由基本使用仍是满简单的,零碎的小东西有点多,因此我直接把他们揉到一块儿作了一个小例子,代码我都写上注释了,应该挺简单易懂的react-router

注意:如下全部操做均运行在搭好的React环境中dom

这个小例子里主要有路由的使用,精准匹配,路由的高亮,子路由,包容性路由变为排他性路由,动态路由,路由转化spa

 

1.安装react-router-domcode

  yarn add  react-router-domcomponent

 

2.而后咱们直接上代码,照着代码操做就能够了router

import React, { Component } from 'react' import './index.css' import { Route, Switch, Link, Redirect, NavLink, BrowserRouter as Router } from 'react-router-dom' class Home extends Component{ render(){ return ( <Router>
           <div>
               <ul>

                   <NavLink to="/food" activeClassName="active">food</NavLink><hr/>
                   <NavLink to="/wiki" activeClassName="active">wiki</NavLink><hr/>
                   <NavLink to="/profile" activeClassName="active">profile</NavLink><hr/>
               </ul>
 {/* 使用Switch是为了将React默认的包容性路由变为排他性路由 */} {/* 包容性路由:/food 既能匹配到/ 又能匹配到/food 排他性路由:只能匹配一个 /food就只能匹配到/food */} <Switch> {/*Redirect 是路由转化 即匹配到某一个路由转化到另外一个路由 */} <Redirect from="/" exact to="/food"/>
                       <Route path="/food" component={Food}/>
                         {/* 除了用Switch外也能够用exact来避免一个路由匹配多个,exact是精准匹配 可是使用exact时须要每一个路由上都加上exact才能达到和Switch同样的效果 */} {/* <Route path="/wiki" exact component={Wiki}/> */} <Route path="/wiki" component={Wiki}/>
                       <Route path="/profile" component={Profile}/>
                       <Route component={Page404}/>
                   </Switch>
           </div>
        </Router>
 ) } } //定义路由使用的组件

    //在Food中定义子路由
const Food = () => ( <div>
        <Link to="/food/foodlist/3">foodlist</Link><br/>
        <Link to="/food/foodmenu">foodmenu</Link>
        <Route path="/food/foodlist/:id" component = {Foodlist}></Route>
        <Route path="/food/foodmenu" component = {Foodmenu}></Route>
    </div>
 ) const Wiki = () => ( <div>Wiki</div>
 ) const Profile = () => ( <div>profile</div>
 ) const Page404 = () => ( <div>page not found.</div>
 ) //定义路由使用的组件结束

  

  //子路由调用的组件
  const Foodlist = () => ( <div>子路由的Foodlist</div>
 ) const Foodmenu = () => ( <div>子路由的Foodmenu</div>
 ) export default Home

 

 

特别注意:/index.css是我引入的一个高亮的样式blog

  

index.css里面的代码路由

.active { font-size: 50px;
  }

 

运行结果:

 

这个运行结果丑是丑了点,可是功能没瑕疵,和我同样,不靠颜值吃饭

相关文章
相关标签/搜索