<BrowserRouter> 使用 HTML5 提供的 history API (pushState, replaceState 和 popstate 事件) 来保持 UI 和 URL 的同步。node
<BrowserRouter basename={string} forceRefresh={bool} getUserConfirmation={func} keyLength={number} >
basename: string
全部位置的基准 URL。若是你的应用程序部署在服务器的子目录,则须要将其设置为子目录。basename 的正确格式是前面有一个前导斜杠,但不能有尾部斜杠。
例子:react
<BrowserRouter basename="/calendar"> <Link to="/today" /> </BrowserRouter>
效果:ajax
<a href="/calendar/today" />
forceRefresh: bool
若是为 true ,在导航的过程当中整个页面将会刷新。通常状况下,只有在不支持 HTML5 history API 的浏览器中使用此功能。
例子:浏览器
const supportsHistory = 'pushState' in window.history; <BrowserRouter forceRefresh={!supportsHistory} />
getUserConfirmation: func
用于确认导航的函数,默认使用 window.confirm。例如,当从 /a 导航至 /b 时,会使用默认的 confirm 函数弹出一个提示,用户点击肯定后才进行导航,不然不作任何处理。译注:须要配合 <Prompt> 一块儿使用。服务器
// 这是默认的确认函数 const getConfirmation = (message, callback) => { const allowTransition = window.confirm(message); callback(allowTransition); } <BrowserRouter getUserConfirmation={getConfirmation} />
KeyLength:数字,设置Location.Key的长度;react-router
使用 URL 的 hash 部分(即 window.location.hash)来保持 UI 和 URL 的同步。app
<HashRouter basename={string} getUserConfirmation={func} hashType={string} > <App /> </HashRouter>
basename,getUserConfirmation和BrowserRouter功能同样dom
hashType: string
window.location.hash 使用的 hash 类型,有以下几种:
slash - 后面跟一个斜杠,例如 #/ 和 #/sunshine/lollipops
noslash - 后面没有斜杠,例如 # 和 #sunshine/lollipops
hashbang - Google 风格的 ajax crawlable,例如 #!/ 和 #!/sunshine/lollipops
默认为 slash。函数
为你的应用提供声明式的、可访问的导航连接。
注:必需要有to属性,不然页面报错动画
this.props.history.push({ pathname:"/inbox", query:{ name:"inbox", myas:"哈哈" } }) <Link to="/about" >About</Link>
to: string
一个字符串形式的连接地址,经过 pathname、search 和 hash 属性建立。
<Link to='/courses?sort=name' />
to: object
一个对象形式的连接地址,能够具备如下任何属性:
pathname - 要连接到的路径
search - 查询参数
hash - URL 中的 hash,例如 #the-hash
state - 存储到 location 中的额外状态数据
<Link to={{ pathname: '/courses', search: '?sort=name', hash: '#the-hash', query: { id: '', } state: { fromDashboard: true } }} />
replace: bool
当设置为 true 时,点击连接后将替换历史堆栈中的当前条目,而不是添加新条目。默认为 false。
<Link to="/courses" replace />
一个特殊版本的 <Link>,它会在与当前 URL 匹配时为其呈现元素添加样式属性。
<NavLink to="/about">About</NavLink>
activeClassName: string
当元素处于激活状态时应用的类,默认为 active。它将与 className 属性一块儿使用。
<NavLink to="/faq" activeClassName="selected">FAQs</NavLink>
activeStyle: object
当元素处于激活状态时应用的样式。
const activeStyle = { fontWeight: 'bold', color: 'red' }; <NavLink to="/faq" activeStyle={activeStyle}>FAQs</NavLink>
用于在位置跳转以前给予用户一些确认信息。当你的应用程序进入一个应该阻止用户导航的状态时(好比表单只填写了一半),弹出一个提示。
import { Prompt } from 'react-router-dom'; <Prompt when={formIsHalfFilledOut} message="你肯定要离开当前页面吗?" />
message: string
当用户试图离开某个位置时弹出的提示信息。
<Prompt message="你肯定要离开当前页面吗?" />
message: func
将在用户试图导航到下一个位置时调用。须要返回一个字符串以向用户显示提示,或者返回 true 以容许直接跳转。
<Prompt message={location => { const isApp = location.pathname.startsWith('/app'); return isApp ? `你肯定要跳转到${location.pathname}吗?` : true; }} />
when: bool
在应用程序中,你能够始终渲染 <Prompt> 组件,并经过设置 when={true} 或 when={false} 以阻止或容许相应的导航,而不是根据某些条件来决定是否渲染 <Prompt> 组件。
译注:when 只有两种状况,当它的值为 true 时,会弹出提示信息。若是为 false 则不会弹出。
<Prompt when={true} message="你肯定要离开当前页面吗?" />
使用 <Redirect> 会导航到一个新的位置。新的位置将覆盖历史堆栈中的当前条目,例如服务器端重定向(HTTP 3xx)。
import { Route, Redirect } from 'react-router-dom'; <Route exact path="/" render={() => ( loggedIn ? ( <Redirect to="/dashboard" /> ) : ( <PublicHomePage /> ) )} />
to: string
要重定向到的 URL。
<Redirect to="/somewhere/else" />
to: object
要重定向到的位置,其中 pathname 能够是可以理解的任何有效的 URL 路径。
<Redirect to={{ pathname: '/login', search: '?utm=your+face', state: { referrer: currentLocation } }} />
例中的 state 对象能够在重定向到的组件中经过 this.props.location.state 进行访问。
push: bool
若是为 true,重定向会将新的位置推入历史记录,而不是替换当前条目。
<Redirect push to="/somewhere/else" />
exact:bool
若是为 true,则只有在 path 彻底匹配 location.pathname 时才匹配。
<Route exact path="/one" component={OneComponent} />
path: string
<Route path="/users/:id" component={User} />
没有定义 path 的 <Route> 老是会被匹配。
render: func
使用 render 能够方便地进行内联渲染和包装,而无需进行上文解释的没必要要的组件重装。
// 方便的内联渲染
<Route path="/home" render={() => <div>Home</div>} />
component
指定只有当位置匹配时才会渲染的 React 组件,该组件会接收 route props 做为属性。
const User = ({ match }) => { return <h1>Hello {match.params.username}!</h1> } <Route path="/user/:username" component={User} />
children: func
有时候不论 path 是否匹配位置,你都想渲染一些内容。在这种状况下,你可使用 children 属性。除了不管是否匹配它都会被调用之外,它的工做原理与 render 彻底同样。
children 渲染方式接收全部与 component 和 render 方式相同的 route props,除非路由与 URL 不匹配,不匹配时 match 为 null。这容许你能够根据路由是否匹配动态地调整用户界面。以下所示,若是路由匹配,咱们将添加一个激活类:
const ListItemLink = ({ to, ...rest }) => ( <Route path={to} children={({ match }) => ( <li className={match ? 'active' : ''}> <Link to={to} {...rest} /> </li> )} /> ) <ul> <ListItemLink to="/somewhere" /> <ListItemLink to="/somewhere-else" /> </ul>
这对动画也颇有用:
<Route children={({ match, ...rest }) => ( {/* Animate 将始终渲染,所以你能够利用生命周期来为其子元素添加进出动画 */} <Animate> {match && <Something {...rest} />} </Animate> )} />
警告:<Route component> 和 <Route render> 优先于 <Route children>,所以不要在同一个 <Route> 中同时使用多个。
组件中
1) path
每一个 Route 都须要定义一个 path 属性,当使用 BrowserRouter 时,path 用来描述这个Router匹配的 URL 的pathname;当使用 HashRouter时,path 用来描述这个 Route 匹配的 URL 的 hash。例如,使用 BrowserRouter 时,<Route path=''foo' /> 会匹配一个 pathname 以 foo 开始的 URL (如: http://example.com/foo)。当 URL 匹配一个 Route 时,这个 Route 中定义的组件就会被渲染出来。
2) match
当 URL 和 Route匹配时,Route 会建立一个 match 对象做为 props 中的一个 属性传递给被渲染的组件。这个对象包含如下4个属性。
(1)params: Route的 path 能够包含参数,例如 <Route path="/foo/:id" 包含一个参数 id。params就是用于从匹配的 URL 中解析出 path 中的参数,例如,当 URL = 'http://example.ocm/foo/1' 时,params= {id: 1}。
(2)isExact: 是一个布尔值,当 URL 彻底匹时,值为 true; 当 URL 部分匹配时,值为 false.例如,当 path='/foo'、URL="http://example.com/foo" 时,是彻底匹配; 当 URL="http://example.com/foo/1" 时,是部分匹配。
(3)path: Route 的 path 属性,构建嵌套路由时会使用到。
(4)url: URL 的匹配的方式
3) history对象
history对象一般具备如下属性和方法:
length : (number)历史堆栈中的条目数
action : (string)当前动做(PUSH,REPLACE或POP)
location : (object) 当前位置。
具备如下属性:
pathname: URL的路径
search: URL查询字符串
hash: URL哈希片断
state: 位置特定的状态被提供给例如。当这个位置被推到堆栈上时,push(路径,状态)。仅在浏览器和内存历史记录中可用。
push : (path, [state]) - (function) 将新条目推入历史堆栈
replace : (path, [state]) - (function) 替换历史堆栈上的当前条目
go(n) : (function) 将历史堆栈中的指针移动n个条目
goBack() : (function) 至关于 go(-1)
goForward() : (function) 至关于 go(1)
block : (function) 防止导航
用于渲染与路径匹配的第一个子 <Route> 或 <Redirect>。
这与仅仅使用一系列 <Route> 有何不一样?
<Switch> 只会渲染一个路由。相反,仅仅定义一系列 <Route> 时,每个与路径匹配的 <Route> 都将包含在渲染范围内。考虑以下代码:
<Route path="/about" component={About} /> <Route path="/:user" component={User} /> <Route component={NoMatch} />
若是 URL 是 /about,那么 <About>、<User> 和 <NoMatch> 将所有渲染,由于它们都与路径匹配。这是经过设计,容许咱们以不少方式将 <Route> 组合成咱们的应用程序,例如侧边栏和面包屑、引导标签等。
可是,有时候咱们只想选择一个 <Route> 来呈现。好比咱们在 URL 为 /about 时不想匹配 /:user(或者显示咱们的 404 页面),这该怎么实现呢?如下就是如何使用 <Switch> 作到这一点:
import { Switch, Route } from 'react-router'; <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/:user" component={User} /> <Route component={NoMatch} /> </Switch>
如今,当咱们在 /about 路径时,<Switch> 将开始寻找匹配的 <Route>。咱们知道,<Route path="/about" /> 将会被正确匹配,这时 <Switch> 会中止查找匹配项并当即呈现 <About>。一样,若是咱们在 /michael 路径时,那么 <User> 会呈现。
这对于动画转换也颇有用,由于匹配的 <Route> 与前一个渲染位置相同。
<Fade> <Switch> {/* 这里只会渲染一个子元素 */} <Route /> <Route /> </Switch> </Fade> <Fade> <Route /> <Route /> {/* 这里老是会渲染两个子元素,也有多是空渲染,这使得转换更加麻烦 */} </Fade>
location: object
用于匹配子元素而不是当前历史位置(一般是当前的浏览器 URL)的 location 对象。
children: node
全部 <Switch> 的子元素都应该是 <Route> 或 <Redirect>。只有第一个匹配当前路径的子元素将被呈现。
<Route> 组件使用 path 属性进行匹配,而 <Redirect> 组件使用它们的 from 属性进行匹配。没有 path 属性的 <Route> 或者没有 from 属性的 <Redirect> 将始终与当前路径匹配。
当在 <Switch> 中包含 <Redirect> 时,你可使用任何 <Route> 拥有的路径匹配属性:path、exact 和 strict。from 只是 path 的别名。
若是给 <Switch> 提供一个 location 属性,它将覆盖匹配的子元素上的 location 属性。
<Switch> <Route exact path="/" component={Home} /> <Route path="/users" component={Users} /> <Redirect from="/accounts" to="/users" /> <Route component={NoMatch} /> </Switch>
您能够经过withRouter高阶组件访问历史对象的属性和最接近的<Route>的匹配。随着路由每次路由改变时,路由器会从新渲染其组件,路径与<路径>渲染道具:{match,location,history}相同。