1盗尸、React-Router是什么麸祷?
它是react體系的一個重要部分,它通過管理URL,實現(xiàn)組件的切換和狀態(tài)的變化杭抠,開發(fā)負責(zé)的應(yīng)用幾乎都會用到脸甘。
2、React-Router的基本用法
2.1祈争、安裝:? cnpm? install react-router;
2.2斤程、router和route的關(guān)系:
????????? router是react的一個組件,它本身只是一個容器菩混,真正的路由要通過Route組件定義。在寫路由的時候要先從react-router,導(dǎo)入所需的組件扁藕。
????????? 例如:
說明:
a沮峡、首先我們要從react-rooter中將我們要用到的組件導(dǎo)入進來,見圖1中的第2行亿柑。
b邢疙、IndexRoute組件(見圖1紅色代碼部分)
????? App組件下有兩個子組件,分別為component1和component2組件望薄。當(dāng)我們訪問/路徑的時候疟游,會直接加載component1。IndexRoute指定component1是根路由的子組件痕支,即指定默認(rèn)情況下加載的子組件颁虐。
c、IndexRoute組件沒有路徑參數(shù)path卧须。
3另绩、IndexRedirect組件
IndexRedirect組件用于訪問根路由的時候,將用戶重定向到某個子組件花嘶。
<Route path="/" component={App}>
?????? <IndexRedirect? to="./component1"/>
?????? <Route? path="component1"? component={component1} />
?????? <Route? path="component2"? component={component2} />
</Route>
代碼中笋籽,用戶訪問根路徑時,將自動重定向到子組件component1椭员。
4车海、Link組件
Link組件用于取代<a>元素,生成一個鏈接隘击,允許用戶點擊后跳轉(zhuǎn)到另一個路由侍芝。它基本上是<a>元素的React版本研铆,可以接收Router的狀態(tài)。
render(){
?? return
<div>
????????? <ul role="nav">
?????????????? <li><link to="/component1">Component1</link></li>
?????????????? <li><link to="/component2">Component2</link></li>
?????? ? </ul>
</div>
? } ???
??????
??????