React Router 中文文档(一)
官方英文文档 - https://reacttraining.com/rea... <BrowserRouter>
import { BrowserRouter } from 'react-router-dom'; <BrowserRouter basename={string} forceRefresh={bool} getUserConfirmation={func} keyLength={number} > <App /> </BrowserRouter> basename: string所有位置的基准 URL。如果你的应用程序部署在服务器的子目录,则需要将其设置为子目录。 <BrowserRouter basename="/calendar"> <Link to="/today" /> </BrowserRouter> 上例中的 <a href="/calendar/today" /> forceRefresh: bool如果为 const supportsHistory = 'pushState' in window.history; <BrowserRouter forceRefresh={!supportsHistory} /> getUserConfirmation: func用于确认导航的函数,默认使用 window.confirm。例如,当从 // 这是默认的确认函数 const getConfirmation = (message,callback) => { const allowTransition = window.confirm(message); callback(allowTransition); } <BrowserRouter getUserConfirmation={getConfirmation} /> keyLength: number
<BrowserRouter keyLength={12} /> children: node要呈现的单个子元素(组件)。 <HashRouter>
import { HashRouter } from 'react-router-dom'; <HashRouter> <App /> </HashRouter> 注意: 使用 basename: string所有位置的基准 URL。 <HashRouter basename="/calendar"> <Link to="/today" /> </HashRouter> 上例中的 <a href="#/calendar/today" /> getUserConfirmation: func用于确认导航的函数,默认使用 window.confirm。 // 这是默认的确认函数 const getConfirmation = (message,callback) => { const allowTransition = window.confirm(message); callback(allowTransition); } <HashRouter getUserConfirmation={getConfirmation} /> hashType: string
默认为 children: node要呈现的单个子元素(组件)。 <Link>为你的应用提供声明式的、可访问的导航链接。 import { Link } from 'react-router-dom'; <Link to="/about">About</Link> to: string一个字符串形式的链接地址,通过 <Link to='/courses?sort=name' /> to: object一个对象形式的链接地址,可以具有以下任何属性:
<Link to={{ pathname: '/courses',search: '?sort=name',hash: '#the-hash',state: { fromDashboard: true } }} /> replace: bool当设置为 <Link to="/courses" replace /> innerRef: func允许访问组件的底层引用。 const refCallback = node => { // node 指向最终挂载的 DOM 元素,在卸载时为 null } <Link to="/" innerRef={refCallback} /> others你还可以传递一些其它属性,例如 <Link to="/" className="nav" title="a title">About</Link> <NavLink>一个特殊版本的 import { NavLink } from 'react-router-dom'; <NavLink to="/about">About</NavLink> activeClassName: string当元素处于激活状态时应用的类,默认为 <NavLink to="/faq" activeClassName="selected">FAQs</NavLink> activeStyle: object当元素处于激活状态时应用的样式。 const activeStyle = { fontWeight: 'bold',color: 'red' }; <NavLink to="/faq" activeStyle={activeStyle}>FAQs</NavLink> exact: bool如果为 <NavLink exact to="/profile">Profile</NavLink> strict: bool如果为 <NavLink strict to="/events/">Events</NavLink> isActive: func添加额外逻辑以确定链接是否处于激活状态的函数。如果你要做的不仅仅是验证链接的路径名与当前 URL 的路径名相匹配,那么应该使用它。 // 只有当事件 id 为奇数时才考虑激活 const oddEvent = (match,location) => { if (!match) { return false; } const eventID = parseInt(match.params.eventID); return !isNaN(eventID) && eventID % 2 === 1; } <NavLink to="/events/123" isActive={oddEvent}>Event 123</NavLink> location: object
<Prompt>用于在位置跳转之前给予用户一些确认信息。当你的应用程序进入一个应该阻止用户导航的状态时(比如表单只填写了一半),弹出一个提示。 import { Prompt } from 'react-router-dom'; <Prompt when={formIsHalfFilledOut} message="你确定要离开当前页面吗?" /> message: string当用户试图离开某个位置时弹出的提示信息。 <Prompt message="你确定要离开当前页面吗?" /> message: func将在用户试图导航到下一个位置时调用。需要返回一个字符串以向用户显示提示,或者返回 <Prompt message={location => { const isApp = location.pathname.startsWith('/app'); return isApp ? `你确定要跳转到${location.pathname}吗?` : true; }} />
译注:上例中的
when: bool在应用程序中,你可以始终渲染 译注: <Prompt when={true} message="你确定要离开当前页面吗?" /> <MemoryRouter>将 URL 的历史记录保存在内存中的 import { MemoryRouter } from 'react-router-dom'; <MemoryRouter> <App /> </MemoryRouter> initialEntries: array历史堆栈中的一系列位置信息。这些可能是带有 <MemoryRouter initialEntries={[ '/one','/two',{ pathname: '/three' } ]} initialIndex={1} > <App/> </MemoryRouter> initialIndex: number
getUserConfirmation: func用于确认导航的函数。当 keyLength: number
children: node要呈现的单个子元素(组件)。 <Redirect>使用 import { Route,Redirect } from 'react-router-dom'; <Route exact path="/" render={() => ( loggedIn ? ( <Redirect to="/dashboard" /> ) : ( <PublicHomePage /> ) )} /> to: string要重定向到的 URL,可以是 path-to-regexp 能够理解的任何有效的 URL 路径。所有要使用的 URL 参数必须由 <Redirect to="/somewhere/else" /> to: object要重定向到的位置,其中 <Redirect to={{ pathname: '/login',search: '?utm=your+face',state: { referrer: currentLocation } }} /> 上例中的 push: bool如果为 <Redirect push to="/somewhere/else" /> from: string要从中进行重定向的路径名,可以是 path-to-regexp 能够理解的任何有效的 URL 路径。所有匹配的 URL 参数都会提供给 只能在 <Switch> <Redirect from='/old-path' to='/new-path' /> <Route path='/new-path' component={Place} /> </Switch> // 根据匹配参数进行重定向 <Switch> <Redirect from='/users/:id' to='/users/profile/:id' /> <Route path='/users/profile/:id' component={Profile} /> </Switch> 译注:经过实践,发现以上“根据匹配参数进行重定向”的示例存在bug,没有效果。 exact: bool完全匹配,相当于 Route.exact。 strict: bool严格匹配,相当于 Route.strict。 <Route>
请考虑以下代码: import { BrowserRouter as Router,Route } from 'react-router-dom'; <Router> <div> <Route exact path="/" component={Home} /> <Route path="/news" component={News} /> </div> </Router> 如果应用程序的位置是 <div> <Home /> <!-- react-empty: 2 --> </div> 或者,如果应用程序的位置是 <div> <!-- react-empty: 1 --> <News /> </div> 其中 Route render methods使用
在不同的情况下使用不同的方式。在指定的 Route props三种渲染方式都将提供相同的三个路由属性:
component指定只有当位置匹配时才会渲染的 React 组件,该组件会接收 route props 作为属性。 const User = ({ match }) => { return <h1>Hello {match.params.username}!</h1> } <Route path="/user/:username" component={User} /> 当你使用 render: func使用 你可以传入一个函数,以在位置匹配时调用,而不是使用 // 方便的内联渲染 <Route path="/home" render={() => <div>Home</div>} /> // 包装 const FadingRoute = ({ component: Component,...rest }) => ( <Route {...rest} render={props => ( <FadeIn> <Component {...props} /> </FadeIn> )} /> ) <FadingRoute path="/cool" component={Something} /> 警告: children: func有时候不论
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> )} /> 警告: path: string可以是 path-to-regexp 能够理解的任何有效的 URL 路径。 <Route path="/users/:id" component={User} /> 没有定义 exact: bool如果为 <Route exact path="/one" component={OneComponent} />
strict: bool如果为 <Route strict path="/one/" component={OneComponent} />
警告:可以使用
location: object一般情况下, 当你需要将 如果一个 sensitive: bool如果为 <Route sensitive path="/one" component={OneComponent} />
<Router>所有 Router 组件的通用低阶接口。通常情况下,应用程序只会使用其中一个高阶 Router:
使用低阶 <Router> 的最常见用例是同步一个自定义历史记录与一个状态管理库,比如 Redux 或 Mobx。请注意,将 React Router 和状态管理库一起使用并不是必需的,它仅用于深度集成。 import { Router } from 'react-router-dom'; import createBrowserHistory from 'history/createBrowserHistory'; const history = createBrowserHistory(); <Router history={history}> <App /> </Router> history: object用于导航的历史记录对象。 import createBrowserHistory from 'history/createBrowserHistory'; const customHistory = createBrowserHistory(); <Router history={customHistory} /> children: node要呈现的单个子元素(组件)。 <Router> <App /> </Router> <StaticRouter>一个永远不会改变位置的 这在服务器端渲染场景中非常有用,因为用户实际上没有点击,所以位置实际上并未发生变化。因此,名称是 以下是一个示例,node server 为 import { createServer } from 'http'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { StaticRouter } from 'react-router'; createServer((req,res) => { // 这个 context 对象包含了渲染的结果 const context = {}; const html = ReactDOMServer.renderToString( <StaticRouter location={req.url} context={context}> <App /> </StaticRouter> ); // 如果使用 <Redirect>,context.url 将包含要重定向到的 URL if (context.url) { res.writeHead(302,{ Location: context.url }); res.end(); } else { res.write(html); res.end(); } }).listen(3000); basename: string所有位置的基准 URL。 <StaticRouter basename="/calendar"> <Link to="/today" /> </StaticRouter> 上例中的 <a href="/calendar/today" /> location: string服务器收到的 URL,可能是 node server 上的 <StaticRouter location={req.url}> <App /> </StaticRouter> location: object一个形如 <StaticRouter location={{ pathname: '/bubblegum' }}> <App /> </StaticRouter> context: object一个普通的 JavaScript 对象。在渲染过程中,组件可以向对象添加属性以存储有关渲染的信息。 const context = {}; <StaticRouter context={context}> <App /> </StaticRouter> 当一个 渲染之后,可以使用这些属性来配置服务器的响应。 if (context.status === '404') { // ... } children: node要呈现的单个子元素(组件)。 <Switch>用于渲染与路径匹配的第一个子 这与仅仅使用一系列
<Route path="/about" component={About} /> <Route path="/:user" component={User} /> <Route component={NoMatch} /> 如果 URL 是 但是,有时候我们只想选择一个 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> 现在,当我们在 这对于动画转换也很有用,因为匹配的 <Fade> <Switch> {/* 这里只会渲染一个子元素 */} <Route /> <Route /> </Switch> </Fade> <Fade> <Route /> <Route /> {/* 这里总是会渲染两个子元素,也有可能是空渲染,这使得转换更加麻烦 */} </Fade> location: object用于匹配子元素而不是当前历史位置(通常是当前的浏览器 URL)的 location 对象。 children: node所有
当在 如果给 <Switch> <Route exact path="/" component={Home} /> <Route path="/users" component={Users} /> <Redirect from="/accounts" to="/users" /> <Route component={NoMatch} /> </Switch> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |