• React Router


    一、安装

    安装命令如下:

    $ npm install -S react-router

    使用时,路由器Router就是React的一个组件。

    二、基本用法

    Router组件本身只是一个容器,真正的路由要通过Route组件定义。

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

    上面代码中,用户访问根路由/(比如http://www.example.com/),组件APP就会加载到document.getElementById('app')

    你可能还注意到,Router组件有一个参数history,它的值hashHistory表示,路由的切换由URL的hash变化决定,即URL的#部分发生变化。举例来说,用户访问http://www.example.com/,实际会看到的是http://www.example.com/#/

    Route组件定义了URL路径与组件的对应关系。你可以同时使用多个Route组件。

    <Router history={hashHistory}>
      <Route path="/" component={App}/>
      <Route path="/repos" component={Repos}/>
      <Route path="/about" component={About}/>
    </Router>

    上面代码中,用户访问/repos(比如http://localhost:8080/#/repos)时,加载Repos组件;访问/abouthttp://localhost:8080/#/about)时,加载About组件。

    三、嵌套路由

     你的UI界面可能是这个样子的:

                 +-------------------------------------+
                 | Home Repos About                    | <- App
                 +------+------------------------------+
                  |         |                          |
    Repos->       | repo    |  Repo 1                  |
                  |         |                          |
                  | repo    |  Boxes inside boxes      |
                  |         |  inside boxes ...        | <- Repo
                  | repo    |                          |
                  |         |                          |
                  | repo    |                          |
                  |         |                          |
                 +------+------------------------------+

    我们可以把about和repos组件嵌套进app,因此我们可以在app中所有页面共享导航。我们需要分两步来实现

    首先将Repo和About的Route嵌套进APP中

    <Router history={hashHistory}>
      <Route path="/" component={App}>
        <Route path="/repos" component={Repos}/>
        <Route path="/about" component={About}/>
      </Route>
    </Router>

    然后在APP组件中render进子节点

    render() {
        return (
          <div>
            <h1>React Router Tutorial</h1>
            <ul role="nav">
              <li><Link to="/about">About</Link></li>
              <li><Link to="/repos">Repos</Link></li>
            </ul>
    
            {/* add this */}
            {this.props.children}
    
          </div>
        )
      }

    上面代码中,App组件的this.props.children属性就是子组件。

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

    let routes = <Route path="/" component={App}>
      <Route path="/repos" component={Repos}/>
      <Route path="/about" component={About}/>
    </Route>;
    
    <Router routes={routes} history={browserHistory}/>

    上面代码中,用户访问/repos时,会先加载App组件,然后在它的内部再加载Repos组件。

    <App>
      <Repos/>
    </App>

    四、path属性

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

    请看下面的例子。

    <Route path="inbox" component={Inbox}>
       <Route path="messages/:id" component={Message} />
    </Route>

    上面代码中,当用户访问/inbox/messages/:id时,会加载下面的组件。

    <Inbox>
      <Message/>
    </Inbox>

    如果省略外层Routepath参数,写成下面的样子

    <Route component={Inbox}>
      <Route path="inbox/messages/:id" component={Message} />
    </Route>

    现在用户访问/inbox/messages/:id时,外层的Inbox组件不管路径是否匹配都会加载出来,因此组件加载还是原来的样子。

    <Inbox>
      <Message/>
    </Inbox>

    五、通配符

    <Route path="/hello/:name">
    // 匹配 /hello/michael
    // 匹配 /hello/ryan
    
    <Route path="/hello(/:name)">
    // 匹配 /hello
    // 匹配 /hello/michael
    // 匹配 /hello/ryan
    
    <Route path="/files/*.*">
    // 匹配 /files/hello.jpg
    // 匹配 /files/hello.html
    
    <Route path="/files/*">
    // 匹配 /files/ 
    // 匹配 /files/a
    // 匹配 /files/a/b
    
    <Route path="/**/*.jpg">
    // 匹配 /files/hello.jpg
    // 匹配 /files/path/to/file.jpg

    匹配规则如下:

    (1):paramName

    :paramName匹配URL的一个部分,直到遇到下一个/?#为止。这个路径参数可以通过this.props.params.paramName取出。

    (2)()

    ()表示URL的这个部分是可选的。

    (3)*

    *匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。

    (4) **

    ** 匹配任意字符,直到下一个/?#为止。匹配方式是贪婪模式。

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

    路由匹配规则是从上到下执行,一旦发现匹配,就不再其余的规则了。设置路径参数时,需要特别小心这一点。

    <Router>
      <Route path="/:userName/:id" component={UserPage}/>
      <Route path="/about/me" component={About}/>
    </Router>

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

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

    六、IndexRoute

    当运行下面这个例子时

    <Router>
      <Route path="/" component={App}>
        <Route path="accounts" component={Accounts}/>
        <Route path="statements" component={Statements}/>
      </Route>
    </Router>

    我们直接访问根路径/,不会加载任何子组件。也就是说,App组件的this.props.children,这时是undefined。因此我们想要创建一个Home页,当访问根路径时加载。

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

    <Router>
      <Route path="/" component={App}>
        <IndexRoute component={Home}/>
        <Route path="accounts" component={Accounts}/>
        <Route path="statements" component={Statements}/>
      </Route>
    </Router>

    现在,用户访问/的时候,加载的组件结构如下。

    <App>
      <Home/>
    </App>

    这种组件结构就很清晰了:App只包含下级组件的共有元素,本身的展示内容则由Home组件定义。这样有利于代码分离,也有利于使用React Router提供的各种API。

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

    七、Link

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

    Link和a标签的不同之处在与Link知道它连接到的路径是否处于激活状态,这样你就可以给激活的链接添加不同的样式

    render() {
      return <div>
        <ul role="nav">
          <li><Link to="/about">About</Link></li>
          <li><Link to="/repos">Repos</Link></li>
        </ul>
      </div>
    }

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

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

    上面代码中,当前页面的链接会红色显示。

    另一种做法是,使用activeClassName指定当前路由的Class

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

    封装Link

    你的站点的大多数链接不需要知道他们是否处于激活状态,通常只有主导航需要知道。因此将它封装起来是很有用的。

    import React from 'react'
    import { Link } from 'react-router'
    
    export default React.createClass({
      render() {
        return <Link {...this.props} activeClassName="active"/>
      }
    })

    这样你不需要管理随处都有的activeClassName和activeStyle.

    需要使用时可以直接引入上面的组件,

    <li><NavLink to="/about">About</NavLink></li>
    <li><NavLink to="/repos">Repos</NavLink></li>

    八、IndexLink

    如果我们想要在链接到根路由/时,处于Active状态,如果我们这样使用

    // APP.js
    <li><NavLink to="/">Home</NavLink></li>

    你会发现很奇怪的事情,Home链接一直都是active状态,因为当子组件的路径处于激活状态时,父组件也会处于激活状态,而/是所有组件的父组件,因此它会一直处于active状态。如果希望只在indexRoute激活时处于active状态,有两种方法:

    1. IndexLink

    <IndexLink to="/" activeClassName="active">
      Home
    </IndexLink>

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

    2. 使用Link组件的onlyActiveOnIndex属性

    <Link to="/" activeClassName="active" onlyActiveOnIndex={true}>
      Home
    </Link>

    因此也可以这样使用

    <li><NavLink to="/" onlyActiveOnIndex={true}>Home</NavLink></li>

    因为我们把所有的属性都传递给了NavLink组件,因此可以这样来实现。

    九、history属性

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

    history属性,一共可以设置三种值:browserHistory、hashHistory、createMemoryHistory.

    如果设为hashHistory,路由将通过URL的hash部分(#)切换,URL的形式类似example.com/#/some/path

    如果设为browserHistory,浏览器的路由就不再通过Hash完成了,而显示正常的路径example.com/some/path,背后调用的是浏览器的History API。但是,这种情况需要对服务器改造。否则用户直接向服务器请求某个子路由,会显示网页找不到的404错误。如果开发服务器使用的是webpack-dev-server,加上--history-api-fallback参数就可以了。

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

    并且在index.html中引入的相对路径改为绝对路径。

    // index.html
    <!-- index.css -> /index.css -->
    <link rel="stylesheet" href="/index.css">
    
    <!-- bundle.js -> /bundle.js(即使bundle.js在/build路径下也是改成这样) -->
    <script src="/bundle.js"></script>

    createMemoryHistory主要用于服务器渲染。它创建一个内存中的history对象,不与浏览器URL互动。

    const history = createMemoryHistory(location)

    十、Redirect组件

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

    <Route path="inbox" component={Inbox}>
      {/* 从 /inbox/messages/:id 跳转到 /messages/:id */}
      <Redirect from="messages/:id" to="/messages/:id" />
    </Route>

    现在访问/inbox/messages/5,会自动跳转到/messages/5

    十一、IndexRedirect组件

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

    <Route path="/" component={App}>
      <IndexRedirect to="/welcome" />
      <Route path="welcome" component={Welcome} />
      <Route path="about" component={About} />
    </Route>

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

    十二、表单处理

    处理表单跳转、点击按钮跳转等操作

    <form onSubmit={this.handleSubmit}>
      <input type="text" placeholder="userName"/>
      <input type="text" placeholder="repo"/>
      <button type="submit">Go</button>
    </form>

    第一种方法是使用browserHistory.push

    import { browserHistory } from 'react-router'
    
    // ...
      handleSubmit(event) {
        event.preventDefault()
        const userName = event.target.elements[0].value
        const repo = event.target.elements[1].value
        const path = `/repos/${userName}/${repo}`
        browserHistory.push(path)
      },

    第二种方法是使用context对象。

    export default React.createClass({
    
      // ask for `router` from context
      contextTypes: {
        router: React.PropTypes.object
      },
    
      handleSubmit(event) {
        // ...
        this.context.router.push(path)
      },
    })

    复制摘抄自阮老师博客:http://www.ruanyifeng.com/blog/2016/05/react_router.html

  • 相关阅读:
    poi 导出Excel
    【EasyUI】combotree和combobox模糊查询
    多线程和Socket套接字
    io流
    前端页面的语法 jquery javascript ajax
    spring+mybatis
    Exchanger 原理
    CountDownLatch、CyclicBarrier和 Semaphore
    sleep() 、join()、yield()有什么区别
    创建线程的方式及实现
  • 原文地址:https://www.cnblogs.com/YangqinCao/p/6345211.html
Copyright © 2020-2023  润新知