1. 程式人生 > >react-router簡明學習

react-router簡明學習

def child import ansi som 否則 ans cer 符號

前面的話

  路由用來分發請求。後端是提供服務的,所以它的路由是在找controller,前端是顯示頁面的,所以它的路由是在找component。本文將詳細介紹react-router-dom的內容

Router

  Router是路由器組件的低階接口,通常會使用如下某個高階router來替代它

<BrowserRouter>
<HashRouter>
<MemoryRouter>
<NativeRouter>
<StaticRouter>

【BrowserRouter】

  最常用的是BrowserRouter

import { BrowserRouter } from react-router-dom

<BrowserRouter
  basename={optionalString}
  forceRefresh={optionalBool}
  getUserConfirmation={optionalFunc}
  keyLength={optionalNumber}
>
  <App/>
</BrowserRouter>

  1、basename: 當前位置的基準 URL。如果頁面部署在服務器的二級(子)目錄,需要將 basename 設置到此子目錄。 正確的 URL 格式是前面有一個前導斜杠,但不能有尾部斜杠

<BrowserRouter basename="/calendar"/>

  2、getUserConfirmation:當導航需要確認時執行的函數。默認使用 window.confirm

// 使用默認的確認函數
const getConfirmation = (message, callback) => {
  const allowTransition = window.confirm(message)
  callback(allowTransition)
}

<BrowserRouter getUserConfirmation={getConfirmation}/>

  3、forceRefresh:當設置為 true 時,在導航的過程中整個頁面將會刷新。 只有當瀏覽器不支持 HTML5 的 history API 時,才設置為 true

const supportsHistory = pushState in window.history
<BrowserRouter forceRefresh={!supportsHistory}/>

  4、keyLength:location.key 的長度。默認是 6

<BrowserRouter keyLength={12}/>

  5、BrowserRouter只能渲染單一子元素

Route

  Route是react-router中最重要的組件,用來匹配請求並渲染相應組件

  1、path 路徑的匹配值,可以包括以下幾種特殊符號

:paramName – 匹配一段位於 /、? 或 # 之後的 URL。 命中的部分將被作為一個參數
() – 在它內部的內容被認為是可選的
* – 匹配任意字符(非貪婪的)直到命中下一個字符或者整個 URL 的末尾,並創建一個 splat 參數

  例子如下所示:

<Route path="/hello/:name">         // 匹配 /hello/michael 和 /hello/ryan
<Route path="/hello(/:name)">       // 匹配 /hello, /hello/michael 和 /hello/ryan
<Route path="/files/*.*">           // 匹配 /files/hello.jpg 和 /files/path/to/hello.jpg

  2、component 要顯示的組件

import { BrowserRouter as Router, Route } from react-router-dom

<Router>
  <div>
    <Route exact path="/" component={Home}/>
    <Route path="/news" component={NewsFeed}/>
  </div>
</Router>

  3、render 函數中return的值就是要顯示的內容

<Route path="/home" render={() => <div>Home</div>}/>

  4、children 與render的區別在於,不管有沒有匹配,都想顯示的內容

const ListItemLink = ({ to, ...rest }) => (
  <Route path={to} children={({ match }) => (
    <li className={match ? active : ‘‘}>
      <Link to={to} {...rest}/>
    </li>
  )}/>
)

  [註意]component/render/children只能三個選一個使用

【匹配規則】

  默認地,路由進行寬松匹配。在下面例子中,路由匹配到/one時,既顯示組件A,也顯示組件B

<Route  path="/one" component={A}/>
<Route  path="/one/two" component={B}/>

  如果要進行確切匹配,則需要添加exact屬性。這樣,路由匹配到/one時,只顯示組件A

<Route  exact path="/one" component={A}/>
<Route  path="/one/two" component={B}/>

  還有一種是嚴格匹配,即斜杠也必須嚴格匹配。下面例子中,路由匹配到/one/時,會顯示組件A,但匹配到/one時,什麽都不會顯示

<Route  strict path="/one/" component={A}/>

  [註意]嚴格匹配並不是確切匹配。下面例子中,路由匹配到/one時,即顯示組件A,也顯示組件B

<Route  strict path="/one" component={A}/>
<Route  path="/one/two" component={B}/>

  如果要確切匹配,則需要

<Route  exact strict path="/one" component={A}/>

  但是,一般地,strict屬性很少使用

【屬性】

  Route默認攜帶三個props:包括match、location、history

  如果使用component,則使用this.props來獲取,如果是render,則在回調函數中使用參數(props)=>{}來獲取

  1、match

  match包括以下屬性

params 鍵值對
isExact 是否確切匹配
path 路徑中設置的值
url URL中的path值

  2、location

  location中包含如下屬性

  [註意]直接訪問location,而不是訪問history.location

{
  key: ac3df4, // not with HashHistory!
  pathname: /somewhere
  search: ?some=search-string,
  hash: #howdy,
  state: {
    [userDefined]: true
  }
}

  通過Link傳遞的state,可以在location中獲取到

  [註意]剛開始時,或者直接刷新瀏覽器,state是沒有值的,只有跳轉到該鏈接時,state才有值。再後來,刷新也有值了

  3、history

  history包含如下屬性

length: history棧的長度
action: 當前的action
location: 當前的location對象

  history包含如下方法

push()
goBack() = go(-1)
goForward() = go(1)
go() 跳轉到 history棧中的哪個enter
replace(path, [state]) 替換history棧中的當前entry
push(path, [state])  添加當前entry到history棧中

Redirect

  Redirect將頁面導航到新位置,新位置將覆蓋history棧中的當前位置,類似於服務器端的重定向(HTTP 3xx)

  to屬性可以是一個字符串,表示跳轉的地址

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>

  to屬性也可以是一個對象

<Redirect to={{
  pathname: /login,
  search: ?utm=your+face,
  state: { referrer: currentLocation }
}}/>

  push屬性為true時,表示添加新記錄到history棧中,而不是替換當前記錄

<Redirect push to="/somewhere/else"/>

Link

  Link是對a標簽的封裝,提供無刷新的頁面跳轉。Link標簽主要的屬性是to屬性

  1、一般地,to是一個字符串

<Link to="/about">關於</Link>

  2、也可以寫成對象的形式

<Link to={{
  pathname: /courses,
  search: ?sort=name,
  hash: #the-hash,
  state: { fromDashboard: true }
}}/>

  [註意]在Link裏的子組件或同組件的點擊事件,最好加上阻止默認行為和阻止冒泡

<Link>
  <div onclick={}></div>
</Link>
<Link onclick={}>

【NavLink】

  NavLink相對於Link來說,增加了一些樣式屬性

  activeClassName表示被匹配的a標簽的樣式名;activeStyle表示被匹配的a標簽的樣式

<NavLink
  to="/faq"
  activeClassName="selected"
>FAQs</NavLink>
<NavLink
  to="/faq"
  activeStyle={{
    fontWeight: bold,
    color: red
   }}
>FAQs</NavLink>

Switch

  渲染Route或Redirect匹配到的第一個子元素

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>

  [註意]switch必須直接包括Route,中間不可包含div,否則不生效

react-router簡明學習