首页 > 其他 > 详细

React 路由

时间:2020-04-23 01:40:48      阅读:69      评论:0      收藏:0      [点我收藏+]

路由 React-Router

最新的路由的版本是5.1.2的版本。里面的话提供了一些包

在做web端开发的时候只需要安装react-router-dom就可以了,因为react-router-dom内部就已经包含了最核心的内容。

路由的简单使用

  1. 安装

    yarn  add react-router-dom
  2. 使用

    • 在 index.js 中

      // 1. 导入
      import { HashRouter as Router} from ‘react-router-dom‘
      import {Router} from ‘react-router-dom‘
      ?
      ReactDOM.render(
          // 2. 使用 Router 包裹最外层组件     
         <Router>
            <App />
         </Router>,
        document.getElementById(‘root‘)
      );
      • HashRouter 路径带有 “#” 号, 带有哈希值的形式。

      • Router 不带“#”号

    • 在 App.js 中

      // 1. 引入(其它略..)
      import { Route, Redirect, Switch } from ‘react-router-dom‘
      ?
      export default class App extends Component {
        render() {
          return (
            <div>
              {/* 2. 使用 */}
              <Switch>
                <Route path="/home" component={Home} exact></Route>
                <Route path="/home/a" render = {() => {return <div>/home/a</div>}}></Route>
                <Route path="/article" component={Article} exact></Route>
                <Route path="/article/:id" component={ArticleDetail}></Route>
                <Route path="/404" component={NotFount}></Route>
                <Redirect to="/home" from="/"></Redirect>
                <Redirect to="/404"></Redirect>
              </Switch>
            </div>
          )
        }
      }
      • Route

        • path = "路径"

        • component = {组件} { Route Component }

        • render = { () => { return jsx 代码 } } { Route Render }

        • exact 完全匹配, 默认是模糊匹配。模糊匹配以一个目录为准 如匹配“/home” : "/home/hdsfhs"能匹配到 ,“/homedfsdfsdfadsf”匹配不上

      • Redirect

        • to=" 路径 " 重定向路径

        • from="路径" 需要重定向的路径

      • Switch 匹配到一个后,后面的就不会再匹配

  3. 路由跳转

    App.js

    import { NavLink as Link } from ‘react-router-dom‘
    ?
    <ul style={{listStyle:"none"}}>
        <li><Link to="/home">首页</Link></li>
        <li><Link to="/article">文章列表</Link></li>
    </ul>

    Article.js

    import { Link } from ‘react-router-dom‘
    import { NavLink as Link } from ‘react-router-dom‘
    ?
    <Link to="/article/1">文章1</Link>
    <Link to="/article/1">文章2</Link>
    • Link 路由跳转

      • to = "路径" 跳转到的路径

      • NavLink 点击到的元素带 class = active

 

二级路由与动态跳转

App.js

<Route path="/article" component={Article}></Route>
<Route path="/article/:id" component={ArticleDetail}></Route>

Article.js

<Link to="/article/1">文章1</Link>
<Link to="/article/2">文章2</Link>

ArticleDetail.js

render() {
    // 拿到id
    console.log(this.props.match.params.id)
    return (
        <div>
            ArticleDetail
        </div>
    )
}

 

  • path="/article/:id" : 动态路由书写形式 “/:xxx”

  • to="/article/1" : 参数1 对应 :id

  • 在ArticleDetail.js 中拿到Article.js中传递过来的参数

    • this.props.match.params.id

      拿到 id 就可以根据 id 去请求数据了

路由常用的api方法

render

App.js

<Route path="/home" component={Home} exact></Route>
<Route path="/home" render = {routeProps => {return <Home {...{routeProps}}/>}} exact></Route>

两者具有一样的页面效果

  • render值是一个函数 可以返回 jsx 代码

  • routeProps参数 把它绑定到组件上可以让以{ Route render } 路由形式能够像路由组件一样通过 this.props 拿到以下对象

    只要在路由上绑定了的组件就会有一些路由属性,在组件内部通过this.props 获取

    this.props

    history: {length: 50, action: "POP", location: {…}, createHref: ƒ, push: ƒ, …}

    location: {pathname: "/home", search: "", hash: "", state: undefined}

    match: {path: "/home", url: "/home", isExact: true, params: {…}}

    staticContext: undefined

 

Link参数传递

  1. 可以通过动态路由的方式进行参数传递

    path="/detail/:id"

    Detail组件内部可以通过 this.props.match.params.id可以获取到动态参数

    this.props.match

    1. path: "/article/:id"

    2. url: "/article/2"

    3. isExact: true

    4. params: {id: "2"} 动态路由的参数

  2. 可以通过query进行传参

    Article.js

    <Link to="/article/1?title=文章1">文章1</Link>
    • to="/article/1?title=文章1"问号后面携带参数

    • ArticleDetail组件内部可以通过 this.props.location.search可以获取到 “?title=文章一”

    this.props.location

    1. pathname: "/article/1"

    2. search: "?title=文章1" 地址栏查询字符串

    3. hash: ""

    4. state: null

  3. 可以通过state进行隐式传参

    Article.js

    <Link to={{
        pathname:"/article/2",
        state:{
            title:"文章2"
        }
    }}>文章2</Link>
    • to 的值可以是一个对象,这个对象可以定义跳转路径和携带参数

      • pathname 跳转路径

      • state:对象 对象里面书写携带的参数

    • ArticleDetail组件内部可以通过 this.props.location.state.title可以获取到参数

 

通过history 跳到指定路径

backHome = () => {
    // 1. 跳转到指定路径
    this.props.history.push(‘/home‘)
    // 2. 参数为一个对象
    this.props.history.push({
        pathname:"/home", 
        state:{
            id:123
        }
    })
}
?
<button onClick={this.backHome}>返回首页</button>
  • push("路径") 跳转到指定路由路径

  • push(对象)

    • pathname 路径名称

    • state:{id:123} 携带参数跳转

this.props.history

  1. length: 50

  2. action: "POP"

  3. location: {pathname: "/article/2", search: "", hash: "", state: undefined}

  4. createHref: ƒ createHref(location)

  5. push: ƒ push(path, state) 设置跳转路径

  6. replace: ƒ replace(path, state)

  7. go: ƒ go(n)

  8. goBack: ƒ goBack()

  9. goForward: ƒ goForward()

  10. block: ƒ block(prompt)

  11. listen: ƒ listen(listener)

 

withRouter

withRouter是一个高阶组件,可以把普通组件变成路由组件,让普通组件路由组件一样拥有路由属性(history, location, match)

  1. 引入

    import {withRouter} from "react-router-dom" 
  2. 使用

    import React, { Component } from ‘react‘
    import {withRouter} from ‘react-router-dom‘
    ?
    class BackHome extends Component {
        backHome = () => {
            // 返回首页
            this.props.history.push({
                pathname:"/home", 
                state:{
                    id:123
                }
            })
        }
    ?
        render() {
            return (
                <div>
                    <button onClick={this.backHome}>返回首页</button>
                </div>
            )
        }
    }
    // *******
    export default withRouter(BackHome)

小结

yarn add react-router-dom

导入

1. import { BrowserRouter as Rotuer, HashRouter as Router} from "react-router-dom"
2. import { Route, Redirect, Switch} from "react-router-dom"
3. import { Link, NavLink as Link } from "react-router-dom"
4. import { withRouter } from "react-router-dom"

配置了路由的组件的属性

this.props.match.params.id

this.props.location.state.id

this.props.location.search

this.props.history.push()

 

path="/article/:id"

to="/article/1?title = ‘文章1’ "

 

React 路由

原文:https://www.cnblogs.com/poki/p/12757937.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!