react路由的簡單使用

2021-10-18 17:14:11 字數 2212 閱讀 4940

在相關元件中匯入路由

import

from 'react-router-dom'

(2)、route:表示乙個路由規則,在route上有2個比較重要的屬性:path、component;route等同於vue中的每乙個路由規則(

import react,  from 'react'

import

from 'react-router-dom'

import testlink1 from './views/testlink1.js'

import testlink2 from './views/testlink2.js'

class todolist extends component

render(

)>

//加入exact表示精確匹配

"/testlink2" component=

exact>

)}}export default todolist

注意:

a、在hashrouter內部只能有乙個根節點;在乙個**中,只需要使用唯一的一次即可

b、route建立的標籤,就是路由的規則,path表示要匹配的路由,component表示要展示的元件;route是乙個佔位符,

表示將來匹配到的元件都放到這個位置

​ c、預設情況下,路由是模糊匹配的,也可以進行精確匹配,只需要加上exact屬性即可

d、如果要匹配引數,可以在匹配規則中使用  :   修飾符,表示這個位置匹配到的是引數;冒號(:)後面跟的是引數名**加粗樣式**
this.state =

}}>鏈結1

"/testlink1/:id/:type" component=

exact>

或者使用js的方式:this.props.history.push(/$`

})

在另乙個頁面中這樣接收

console.log(this.props.match.params)
(2)、useparams傳參

**注意:在react17.x中,userparams的方式只能在普通function元件中獲取引數,在class建立的元件中是不能使用的**
this.state =

}}>鏈結1

"/testlink1/:id/:type" component=

exact>

獲取引數方法

import react,  from 'react'

import

from 'react-router-dom'

export default function testlink1

} render(

)= useparams(

) return(

我是testlink1

)}}

(3)、query傳參

這種方式說實話我是很少用到的,因為重新整理的時候引數就不見了

路由頁面:'/demo' component=

>

//無需配置

路由跳轉並傳遞引數:}}

>xx

js方式:this.props.history.push(})

獲取引數: this.props.location.query.name

(4)、state傳參

(重新整理頁面後引數不消失,state傳的引數是加密的,比query傳參好 ;但是state 傳參的方式只支援browserrouter路由,不支 持hashrouter

路由頁面:'/demo' component=

>

//無需配置

路由跳轉並傳遞引數:}}

>xx

js方式:this.props.history.push(})

獲取引數: this.props.location.state.name

React路由的使用

cnpm install react router dom simport react,from react 路由的2種形式 hash hashrouter h5的historyapi broswerrouter 是路由的容器,是元件,要包在路由的外面 import from react route...

簡單粗暴的react路由

習慣了 vue router 路由的用法,再用react router總感覺挺麻煩的。那麼就自己封裝乙個吧 1.封裝多級路由的情況 檔名為routerview.jsimport react from react import from dva router export default props ...

簡單粗暴的react路由

習慣了 vue router 路由的用法,再用react router總感覺挺麻煩的。那麼就自己封裝乙個吧 1.封裝多級路由的情況 檔名為routerview.jsimport react from react import from dva router export default props ...