1、React-Router是什么?
它是react體系的一個重要部分,它通過管理URL,實現(xiàn)組件的切換和狀態(tài)的變化,開發(fā)負(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>
? } ???
??????
??????