react 路由Link配置詳解
1、Link的to屬性
(1)放置路由路徑
(2)放置對象,且為規(guī)定格式
{pathname:"/xx",search:'?鍵值對',hash:"#xxx",state:{鍵值對}}
會自動將pathname、search、hash拼接在url路徑上,state為傳入的參數(shù)
可通過輸出props查看對象內(nèi)的信息
this.props.location.state.鍵名獲取state內(nèi)的數(shù)據(jù)
2、Link的replace屬性
添加replace將跳轉(zhuǎn)前的上一個頁面替換成當(dāng)前頁面,只將當(dāng)前頁面入棧
3、Link傳參
在to路徑后添加"/鍵值"
在路由route,path路徑后添加"/:鍵名"
在組件中,函數(shù)式組件:先傳入props形參,然后props.match.params.鍵名
類組件:this.props.match.params.鍵名
代碼示例:
import React,{Component} from 'react' //import {Route,BrowserRouter,Link} from 'react-router-dom' //將BrowserRouter重命名為Router import {BrowserRouter as Router,Link,Route} from 'react-router-dom' import { Button } from 'antd'; import './App.css'; function Home() { return( <div>admin首頁</div> ) } function Me(props) { console.log(props) return( <div>admin我的</div> ) } function Product(props) { return( <div>admin產(chǎn)品頁面:{props.match.params.id}</div> ) } export default class App extends Component{ constructor() { super(); } render() { {/*若將路徑寫成對象形式,且和下面相同,會自動將pathname、search、hash自動拼接在url路徑上,state為傳入組件的數(shù)據(jù)*/} let obj={pathname:"/me",search:'?username=admin',hash:"#abc",state:{msg:'hello'}} return( <div id='app'> {/*BrowserRouter可以放多個*/} <Router> {/*因為組件也是返回html內(nèi)容,故可以直接通過函數(shù)返回html內(nèi)容充當(dāng)組件,但不能直接寫html內(nèi)容*/} <div> <Route path="/" exact component={()=><div>首頁</div>}></Route> <Route path="/product" component={()=><div>product</div>}></Route> <Route path="/me" component={()=><div>me</div>}></Route> </div> {/*<Route path="/" component={function(){return <div>首頁2</div>}}></Route>*/} </Router> {/*BrowserRouter內(nèi)部只能有一個根容器,包裹其他內(nèi)容*/} {/*添加basename='/xx'后,點擊Link跳轉(zhuǎn)其他路由時,url會將/xx添加到路由名前,所以使用路由路徑和加了admin的路由路徑都能匹配該路由*/} <Router basename='/admin'> <div> <div className='nav'> <Link to='/'>Home</Link> <Link to='/product/123'>Product</Link> {/*可在對應(yīng)的組件中輸出props查看傳入的對象的信息,添加replace將跳轉(zhuǎn)前的上一個頁面替換成當(dāng)前頁面,只將當(dāng)前頁面入棧*/} <Link to={obj} replace>個人中心</Link> </div> <Route path="/" exact component={Home}></Route> <Route path="/product/:id" component={Product}></Route> <Route path="/me" exact component={Me}></Route> </div> </Router> </div> ) } }
到此這篇關(guān)于react 路由Link配置詳解的文章就介紹到這了,更多相關(guān)react 路由Link內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React函數(shù)組件與類組件使用及優(yōu)劣對比
本文主要介紹了React函數(shù)組件與類組件使用及優(yōu)劣對比,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04React基礎(chǔ)-JSX的本質(zhì)-虛擬DOM的創(chuàng)建過程實例分析
這篇文章主要介紹了React基礎(chǔ)-JSX的本質(zhì)-虛擬DOM的創(chuàng)建過程,結(jié)合具體實例形式分析了虛擬dom的基本原理與實現(xiàn)方法,需要的朋友可以參考下2023-05-05React-Native之截圖組件react-native-view-shot的介紹與使用小結(jié)
這篇文章主要介紹了React-Native之截圖組件react-native-view-shot的介紹與使用小結(jié),需本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,要的朋友可以參考下2021-08-08學(xué)習(xí)ahooks useRequest并實現(xiàn)手寫
這篇文章主要為大家介紹了學(xué)習(xí)ahooks useRequest并實現(xiàn)手寫示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03