React-router 基本用法

快来打我* 2022-12-25 15:57 210阅读 0赞

转载自 阮一峰的网络日志 (ruanyifeng.com)

React-router

路由库: ReactTraining/react-router: Declarative routing for React (github.com)

示例库: react-router-tutorial/lessons at master · reactjs/react-router-tutorial (github.com)

文 档: React Router 使用教程 - 阮一峰的网络日志 (ruanyifeng.com)

一、安装:

  1. npm install -S react-router

二、用法:

基础用法

  1. import { Router, Route, hashHistory } from 'react-router';
  2. render((
  3. <Router history={ hashHistory}>
  4. <Route path="/" component={ App}/>
  5. </Router>
  6. ), document.getElementById('app'));

路由嵌套:

  1. // index.js
  2. <Router history={ hashHistory}>
  3. <Route path="/" component={ App}>
  4. <Route path="/repos" component={ Repos}/>
  5. <Route path="/about" component={ About}/>
  6. </Route>
  7. </Router>
  8. // App.js
  9. export default React.createClass({
  10. render() {
  11. return <div>
  12. { this.props.children}
  13. </div>
  14. }
  15. })
  16. // 相当于 先加载App组件,然后在它内部加载Repos组件
  17. <App>
  18. <Repos/>
  19. </App>

routes属性

子路由也可以不写在Router组件里面,单独传入Router组件的routes属性。

  1. let routes = <Route path="/" component={ App}>
  2. <Route path="/repos" component={ Repos}/>
  3. <Route path="/about" component={ About}/>
  4. </Route>;
  5. <Router routes={ routes} history={ browserHistory}/>

三、path属性

Route组件的path属性指定路由的匹配规则。这个属性是可以省略的,这样的话,不管路径是否匹配,总是会加载指定组件。

  1. <Route path="inbox" component={ Inbox}>
  2. <Route path="messages/:id" component={ Message} />
  3. </Route>
  4. // 结果一样
  5. <Route component={ Inbox}>
  6. <Route path="inbox/messages/:id" component={ Message} />
  7. </Route>

四、通配符

path属性可以使用通配符

  1. <Route path="/hello/:name">
  2. // 匹配 /hello/michael
  3. // 匹配 /hello/ryan
  4. <Route path="/hello(/:name)">
  5. // 匹配 /hello
  6. // 匹配 /hello/michael
  7. // 匹配 /hello/ryan
  8. <Route path="/files/*.*">
  9. // 匹配 /files/hello.jpg
  10. // 匹配 /files/hello.html
  11. <Route path="/files/*">
  12. // 匹配 /files/
  13. // 匹配 /files/a
  14. // 匹配 /files/a/b
  15. <Route path="/**/*.jpg">
  16. // 匹配 /files/hello.jpg
  17. // 匹配 /files/path/to/file.jpg
  • paramName 匹配URL的一个部分,直到遇到下一个/ ? # 为止。这个路径参数可以通过 this.props.params.paramName 取出。
  • () 表示URL的这个部分是可选的
  • * 匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。
  • ** 匹配任意字符,直到遇到下一个/ ? # 为止。匹配方式是贪婪模式。

path属性也可以使用相对路径(不以/开头),匹配时就会相对于父组件的路径,可以参考上一节的例子。嵌套路由如果想摆脱这个规则,可以使用绝对路由。

路由匹配规则是从上到下执行,一旦发现匹配,就不再其余的规则了。

注意:设置路径参数时,需要特别小心这一点。

  1. <Router>
  2. <Route path="/:userName/:id" component={ UserPage}/>
  3. <Route path="/about/me" component={ About}/>
  4. </Router>

上面代码中,用户访问/about/me时,不会触发第二个路由规则,因为它会匹配/:userName/:id这个规则。因此,带参数的路径一般要写在路由规则的底部。

此外,URL的查询字符串/foo?bar=baz,可以用this.props.location.query.bar获取。

五、IndexRoute 组件

显式指定Home是根路由的子组件,即指定默认情况下加载的子组件。你可以把IndexRoute想象成某个路径的index.html

  1. <Router>
  2. <Route path="/" component={ App}>
  3. <IndexRoute component={ Home}/>
  4. <Route path="accounts" component={ Accounts}/>
  5. <Route path="statements" component={ Statements}/>
  6. </Route>
  7. </Router>

在访问/ 的时候,加载app组件再加载home组件。<App><Home/></App>

注意,IndexRoute组件没有路径参数path

六、Redirect 组件

Redirect 组件用于路由的跳转,即用户访问一个路由,会自动跳转到另一个路由。

  1. <Route path="inbox" component={ Inbox}>
  2. { /* 从 /inbox/messages/:id 跳转到 /messages/:id */}
  3. <Redirect from="messages/:id" to="/messages/:id" />
  4. </Route>
  5. // 访问/inbox/messages/5,会自动跳转到/messages/5。

七、IndexRedirect 组件

IndexRedirect 组件用于访问根路由的时候,将用户重定向到某个子组件。

  1. <Route path="/" component={ App}>
  2. <IndexRedirect to="/welcome" />
  3. <Route path="welcome" component={ Welcome} />
  4. <Route path="about" component={ About} />
  5. </Route>

用户访问根路径时,将自动重定向到子组件welcome

Link组件用于取代元素,生成一个链接,允许用户点击后跳转到另一个路由。它基本上就是元素的React 版本,可以接收Router的状态。

如果希望当前的路由与其他路由有不同样式,这时可以使用Link组件的activeStyle属性。

  1. <Link to="/about" activeStyle={ { color: 'red'}}>About</Link>
  2. <Link to="/repos" activeStyle={ { color: 'red'}}>Repos</Link>

使用activeClassName指定当前路由的Class

  1. <Link to="/about" activeClassName="active">About</Link>
  2. <Link to="/repos" activeClassName="active">Repos</Link>

Router组件之外,导航到路由页面,可以使用浏览器的History API,像下面这样写。

  1. import { browserHistory } from 'react-router';
  2. browserHistory.push('/some/path');

如果链接到根路由/,不要使用Link组件,而要使用IndexLink组件。

这是因为对于根路由来说,activeStyleactiveClassName会失效,或者说总是生效,因为/会匹配任何子路由。而IndexLink组件会使用路径的精确匹配。

  1. <IndexLink to="/" activeClassName="active">
  2. Home
  3. </IndexLink>

上面代码中,根路由只会在精确匹配时,才具有activeClassName

另一种方法是使用Link组件的onlyActiveOnIndex属性,也能达到同样效果。

  1. <Link to="/" activeClassName="active" onlyActiveOnIndex={ true}>
  2. Home
  3. </Link>

实际上,IndexLink就是对Link组件的onlyActiveOnIndex属性的包装。

十、histroy 属性

Router组件的history属性,用来监听浏览器地址栏的变化,并将URL解析成一个地址对象,供 React Router 匹配。

history属性值:

  • browserHistory 浏览器的路由就不再通过Hash完成了,而显示正常的路径example.com/some/path,背后调用的是浏览器的History API。
  • hashHistory 路由将通过URL的hash部分(#)切换,URL的形式类似example.com/#/some/path
  • createMemoryHistory 主要用于服务器渲染。它创建一个内存中的history对象,不与浏览器URL互动。

使用 browserHistory 属性时:

需要对服务器进行修改【如:nginx配置】。否则用户直接向服务器请求某个子路由,会显示网页找不到的404错误。

如果开发服务器使用的是webpack-dev-server,加上--history-api-fallback参数就可以了。

webpack-dev-server --inline --content-base . --history-api-fallback

十一、表单处理

Link组件用于正常的用户点击跳转 ,但是有时还需要表单跳转、点击按钮跳转等操作。这些情况怎么跟React Router对接呢? [在方法中进行跳转]

第一种方法是使用browserHistory.push

  1. import { browserHistory } from 'react-router'
  2. // ...
  3. handleSubmit(event) {
  4. event.preventDefault()
  5. browserHistory.push('/repos')
  6. }

第二种方法是使用context对象

  1. export default React.createClass({
  2. // ask for `router` from context
  3. contextTypes: {
  4. router: React.PropTypes.object
  5. },
  6. handleSubmit(event) {
  7. // ...
  8. this.context.router.push(path)
  9. },
  10. })

十二、路由的钩子

每个路由都有EnterLeave 钩子,用户进入和离开该路由时触发。

下面是一个例子,使用onEnter钩子替代Redirect组件。

  1. <Route path="inbox" component={ Inbox}>
  2. <Route
  3. path="messages/:id"
  4. onEnter={
  5. ({ params}, replace) => replace(`/messages/${ params.id}`)
  6. }
  7. />
  8. </Route>

onEnter钩子还可以用来做认证。

  1. const requireAuth = (nextState, replace) => {
  2. if (!auth.isAdmin()) {
  3. // Redirect to Home page if not an Admin
  4. replace({ pathname: '/' })
  5. }
  6. }
  7. export const AdminRoutes = () => {
  8. return (
  9. <Route path="/admin" component={ Admin} onEnter={ requireAuth} />
  10. )
  11. }

下面是一个高级应用,当用户离开一个路径的时候,跳出一个提示框,要求用户确认是否离开。

  1. const Home = withRouter(
  2. React.createClass({
  3. componentDidMount() {
  4. this.props.router.setRouteLeaveHook(
  5. this.props.route,
  6. this.routerWillLeave
  7. )
  8. },
  9. routerWillLeave(nextLocation) {
  10. // 返回 false 会继续停留当前页面,
  11. // 否则,返回一个字符串,会显示给用户,让其自己决定
  12. if (!this.state.isSaved)
  13. return '确认要离开?';
  14. },
  15. })
  16. )

上面代码中,setRouteLeaveHook方法为Leave钩子指定routerWillLeave函数。该方法如果返回false,将阻止路由的切换,否则就返回一个字符串,提示用户决定是否要切换。

发表评论

表情:
评论列表 (有 0 条评论,210人围观)

还没有评论,来说两句吧...

相关阅读

    相关 canvas基本

    > canvas是一个强大的绘图及制作动画和游戏手段,下面介绍canvas利用js的API实现基本画图功能。 划线: <!DOCTYPE html> <ht

    相关 QVector基本

    QVector基本用法 QVector是Qt对所有数组的封装,比如我们想要一个int类型数组,我们原先会写int array\[10\],我们在Qt里可以写QVector