日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Raect Router 4 的使用 (1)

發布時間:2023/12/2 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Raect Router 4 的使用 (1) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文來自于官方文檔,屬于意譯而非直譯

  • 基本組件

React Router 有三種類型的組件,分別是:react-router、react-router-dom、react-router-native

你在web 程序中使用了路由組件,那你就應該引入 react-router-dom

import { BrowserRouter, Route, Link } from 'react-router-dom'
  • 路由

React Router 應用程序的的核心是路由組件。對于 web 項目,react-router-dom 提供了?<BrowserRouter> 和?<HashRouter> 路由。這兩種方法都專門創建了 history 對象 。一般來說,

如果你有一個響應請求的服務器,你應該使用??<BrowserRouter> 路由;如果你使用的是靜態文件服務器,你應該使用??<HashRouter> 路由。

import { BrowserRouter } from 'react-router-dom' ReactDOM.render((<BrowserRouter><App/></BrowserRouter> ), holder)

路由組件無法接受兩個及兩個以上的子元素,看一下我自己寫的

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'))

在這接受的是一個 switch 子元素。其實還可以這樣寫:

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'))

其實這個就和官方的例子沒有什么區別了

  • 路由匹配

這里有兩種路由匹配組件:<Route><Switch>

import { Route, Switch } from 'react-router-dom'

路由匹配是通過比較一個 <Route> 的路徑和當前位置的路徑名來完成的。當一個 <Route> 匹配時將渲染匹配到的內容,如果不匹配是將不會渲染。一個<Route> 沒有 path,那它總是匹配的

// when location = { pathname: '/about' } <Route path='/about' component={About}/> // renders <About/> <Route path='/contact' component={Contact}/> // renders null <Route component={Always}/> // renders <Always/>

你可以在你想要渲染內容的位置包含一個 <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>? 并且只渲染當前位置匹配的第一個。當多個路徑匹配到相同的路徑名時,這是非常有幫助的。當在路徑之間進行動畫轉換時,在確定沒有路徑匹配到當前位置時(你可以呈現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>

解釋一下 “只渲染匹配到的第一個” :(http://localhost:8081/#/repos)

<Switch><Route exact path="/repos" component={App}/><Route path="/repos" component={Repos}/><Route path="/about" component={About}/> </Switch>

在這里你只可以看到 App 的內容,看不到 Repos 的內容,因為 App 是匹配到的第一個?


更多專業前端知識,請上 【猿2048】www.mk2048.com

總結

以上是生活随笔為你收集整理的Raect Router 4 的使用 (1)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。