React.js学习笔记(3) - router4路由笔记(1)

2017-08-26  本文已影响81人  woow_wu7

(1) 安装

cnpm install react-router-dom --save

(2) 引入

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'

(3)使用

-(2) exact严格模式,表示只匹配当前的路径。

<Route exact path={ match.url } render={ () => ( <h3>请点击内容查看详情</h3>  ) }></Route>
(上)加了exact (下)没加exact

完整代码:

import React from 'react'
import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom'


const App = () => (
    <Router>
        <div>
            <ul>
                {/*Link的url需要匹配到Route的path,才会渲染对应的组件*/}
                <li> <Link to="/ui">ui站酷</Link> </li>
                <li> <Link to="/code">前端简书</Link> </li>
                <li> <Link to="/dao">省局到</Link> </li>
            </ul>

            <hr/>

            <Route path="/ui" component={ Ui }/>
            <Route path="/code" component={ Code }/>
            <Route path="/dao" component={ Dao }/>
        </div>
    </Router>
)

const Ui = () => (
    <div>
        <h2>
            这里是ui路由的内容
        </h2>
    </div>
)

const Code = () => (
    <div>
        <h2>
            这里是前段路由的内容
        </h2>
    </div>
)

const Dao = ({match}) => {
    console.log(match)
    return(
        <div>
            <h2>这里是胜局到的内容</h2>
            <ul>
                <li> <Link to="/dao/1">省局到内容1</Link> </li>
                <li> <Link to="/dao/2">省局到内容2</Link> </li>
                <li> <Link to="/dao/333">省局到内容3</Link> </li>
                <li> <Link to={ `${match.url}/4`}>省局到内容4</Link> </li>
            </ul>
            <hr/>

            {/*<Route path="/dao/1" render={ () => (<h3>11111111111</h3>)}></Route>*/}
            {/*<Route path="/dao/2" render={ () => (<h3>2222222222</h3>)}></Route>*/}
            {/*<Route path="/dao/3" render={ () => (<h3>333333333</h3>)}></Route>*/}
            <Route path={ `${match.url}/:aa`} component={ Match }></Route>
            {/*这里的:aa表示的是传参,传入aa这个参数变量,获取所有/dao/后面的路径*/}
            <Route exact path={ match.url } render={ () => ( <h3>请点击内容查看详情</h3>  ) }></Route>
        </div>
    )
}
// 下面的match是子路由匹配成功的时候的match,与上面的(父)路由匹配成功的match不一样
const Match = ({match}) => {
    console.log(match)
    return(
        <div>
            <h3>{match.params.aa}</h3>
        </div>
    )
}


export default App
QQ截图20170826024224.png

(官网)https://reacttraining.com/react-router/web/example/basic
http://blog.csdn.net/github_38095237/article/details/70157021?winzoom=1
(嵌套路由)http://www.menvscode.com/detail/5957cdc941d2a6025bbe0446
(简单入门)https://segmentfault.com/a/1190000010174260

上一篇 下一篇

猜你喜欢

热点阅读