React Router

参考:http://www.ruanyifeng.com/blog/2016/05/react_router.html

概念:

路由库是通过管理 URL,实现  “组件”  的切换和状态的变化。关键词是“组件”间。

要完成路由,需要Router 和 Route 两个组件。其中Router组件本身只是一个容器,真正的路由要通过Route组件定义

安装

   npm install -S react-router

引用

   import { Router, Route, hashHistory } from 'react-router';

路由

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

  这句的意思是:
            访问根路径/ 跳转到 APP组件
            访问/repos  跳转到Repos组件
            访问/about  跳转到About组件
  这个有点像java spring 框架中的controller层的路由
  http://localhost:8080/#/repos


  嵌套写法:
  <Router history={hashHistory}> 
        /*嵌套部分*/
        <Route path="/" component={App}> 
              <Route path="/repos" component={Repos}/> 
              <Route path="/about" component={About}/> 
        </Route>
  </Router>

  /*APP.js*/
  /*App组件的this.props.children属性就是子组件*/
  export default React.createClass({ 
          render() { 
                  return <div> {this.props.children} </div> 
          }
  })

  =======================================
  /*换种写法*/
  let routes = <Route path="/" component={App}> 
               <Route path="/repos" component={Repos}/>         
               <Route path="/about" component={About}/>              
               </Route>;

   <Router routes={routes} history={browserHistory}/>

Path

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

   访问/inbox/messages/:id时,会加载
         <Inbox> 
              <Message/>
         </Inbox>

    1.path的配置的通配符:

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

      <Route path="/hello/:name">
      // 匹配 /hello/michael
      // 匹配 /hello/ryan

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

      <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

   2.注意事项
      <Router> 
            <Route path="/:userName/:id" component={UserPage}/> 
            <Route path="/about/me" component={About}/>  
      </Router>

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

   3.IndexRoute
      把IndexRoute想象成某个路径的index.html,IndexRoute组件没有路径参数path。
      <Router> 
          <Route path="/" component={App}> 
              <IndexRoute component={Home}/> 
              <Route path="accounts" component={Accounts}/> 
              <Route path="statements" component={Statements}/> 
          </Route>
      </Router>

Redirect

   <Redirect>组件用于路由的跳转,即用户访问一个路由,会自动跳转到另一个路由。
   <IndexRedirect>组件用于访问根路由的时候,将用户重定向到某个子组件。

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

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

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

Link

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

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

     如果链接到根路由/,不要使用Link组件,而要使用IndexLink组件。这是因为,
     对于根路由来说,activeStyle和activeClassName会失效,或者说总是生效,因为/会匹配任何子路由。
     而IndexLink组件会使用路径的精确匹配。

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

     同样的,onlyActiveOnIndex属性也能实现同样效果
     <Link to="/" activeClassName="active"  onlyActiveOnIndex={true} > 
     Home
     </Link>

History

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

表单

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


  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}`      
            在Router组件之外,导航到路由页面,可以使用浏览器的
            History API,像下面这样写       
            browserHistory.push(path)
   },
    ... ... 

路由的钩子

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

  <Route path="about" component={About} />
  <Route path="inbox" component={Inbox}> 
          <Redirect from="messages/:id" to="/messages/:id" />
  </Route>

  上面的代码中,如果用户离开/messages/:id,进入/about时,会依次触发以下的钩子:
    /messages/:id的onLeave
    /inbox的onLeave
    /about的onEnter
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lesson11、首先确保安装了Node.js和npm依赖包管理工具2、在git上克隆官方示例程序 git clo...
    冰_心阅读 7,590评论 0 16
  • React Router 4.0 (以下简称 RR4) 已经正式发布,它遵循React的设计理念,即万物皆组件。所...
    梁相辉阅读 97,793评论 24 195
  • 概述 传统开发中的 路由,是由服务端根据不同的用户请求地址 URL,返回不同内容的页面,而前端路由则将这些任务通过...
    杨慧莉阅读 4,733评论 1 2
  • 春寒惊雷泣声声,天含情,地悲恸。步履匆匆,千人哭送行。正气清风拂两袖,仁孝悌,情义重。 霜鬓不惑说笑声,月当空,独...
    那年五月阅读 2,895评论 1 2
  • 说起民族唱法,一般人都会认为是各民族或民间的唱法,通俗的说叫“原生态”;了解过的人会知道在音乐学院声乐方向上,有一...
    溪中塵丶阅读 5,378评论 0 1