Raect Router 4 的使用 (1)
本文來(lái)自于官方文檔,屬于意譯而非直譯
- 基本組件
React Router 有三種類型的組件,分別是:react-router、react-router-dom、react-router-native
你在web 程序中使用了路由組件,那你就應(yīng)該引入 react-router-dom:
import { BrowserRouter, Route, Link } from 'react-router-dom'- 路由
React Router 應(yīng)用程序的的核心是路由組件。對(duì)于 web 項(xiàng)目,react-router-dom 提供了?<BrowserRouter> 和?<HashRouter> 路由。這兩種方法都專門創(chuàng)建了 history 對(duì)象 。一般來(lái)說(shuō),
如果你有一個(gè)響應(yīng)請(qǐng)求的服務(wù)器,你應(yīng)該使用??<BrowserRouter> 路由;如果你使用的是靜態(tài)文件服務(wù)器,你應(yīng)該使用??<HashRouter> 路由。
import { BrowserRouter } from 'react-router-dom' ReactDOM.render((<BrowserRouter><App/></BrowserRouter> ), holder)路由組件無(wú)法接受兩個(gè)及兩個(gè)以上的子元素,看一下我自己寫(xiě)的
ReactDom.render((<HashRouter history={hashHistory}><Switch><Route exact path="/" component={App}/><Route path="/repos" component={Repos}/><Route path="/about" component={About}/></Switch></HashRouter> ),document.getElementById('app'))在這接受的是一個(gè) switch 子元素。其實(shí)還可以這樣寫(xiě):
const RoutersComponent = ()=>(<Switch><Route exact path="/" component={App}/><Route path="/repos" component={Repos}/><Route path="/about" component={About}/></Switch> )ReactDom.render((<HashRouter history={hashHistory}><RoutersComponent /> </HashRouter> ),document.getElementById('app'))其實(shí)這個(gè)就和官方的例子沒(méi)有什么區(qū)別了
- 路由匹配
這里有兩種路由匹配組件:<Route> 和 <Switch>
import { Route, Switch } from 'react-router-dom'路由匹配是通過(guò)比較一個(gè) <Route> 的路徑和當(dāng)前位置的路徑名來(lái)完成的。當(dāng)一個(gè) <Route> 匹配時(shí)將渲染匹配到的內(nèi)容,如果不匹配是將不會(huì)渲染。一個(gè)<Route> 沒(méi)有 path,那它總是匹配的
// when location = { pathname: '/about' } <Route path='/about' component={About}/> // renders <About/> <Route path='/contact' component={Contact}/> // renders null <Route component={Always}/> // renders <Always/>你可以在你想要渲染內(nèi)容的位置包含一個(gè) <Route>,但是將 <Route> 放在一起是很有意義的。用 <Switch> 組件將 <Route> 組合在一起:
<Switch><Route exact path='/' component={Home}/><Route path='/about' component={About}/><Route path='/contact' component={Contact}/> </Switch><Switch> 將 <Route> 組合在一起不是必須的,但是是非常有用的。<Switch> 將迭代所有的子元素 <Route>? 并且只渲染當(dāng)前位置匹配的第一個(gè)。當(dāng)多個(gè)路徑匹配到相同的路徑名時(shí),這是非常有幫助的。當(dāng)在路徑之間進(jìn)行動(dòng)畫(huà)轉(zhuǎn)換時(shí),在確定沒(méi)有路徑匹配到當(dāng)前位置時(shí)(你可以呈現(xiàn)404)
<Switch><Route exact path='/' component={Home}/><Route path='/about' component={About}/><Route path='/contact' component={Contact}/>{/* when none of the above match, <NoMatch> will be rendered */}<Route component={NoMatch}/> </Switch>解釋一下 “只渲染匹配到的第一個(gè)” :(http://localhost:8081/#/repos)
<Switch><Route exact path="/repos" component={App}/><Route path="/repos" component={Repos}/><Route path="/about" component={About}/> </Switch>在這里你只可以看到 App 的內(nèi)容,看不到 Repos 的內(nèi)容,因?yàn)?App 是匹配到的第一個(gè)?
更多專業(yè)前端知識(shí),請(qǐng)上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的Raect Router 4 的使用 (1)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Do not mutate vuex s
- 下一篇: this指向问题(2)