react-router

参考资料

安装

  • npm install --save react-router
import { Router, Route, hashHistory, Link } from 'react-router';

创建 router

import App from './modules/App';
import About from './modules/About';

render((
  <Router history={hashHistory}>
    <Route path="/" component={App}/>
    <Route path="/About" component={About}/>
  </Router>
), document.getElementById('app'))

创建 link

import { Link } from 'react-router'

<div>
    <h1>React Router Tutorial</h1>
    <ul role="nav">
        <li><Link to="/about">About</Link></li>
    </ul>
</div>

nested-router

  • 路由
<Router history={hashHistory}>
    <Route path="/app" component={App}>
      <Route path="/about" component={About}/>
    </Route>
</Router>
  • 传子组件到this.props
<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>
  • 得到效果
// at /about
<App>
  <About/>
</App>

link 的选中效果

  • 当路由为/about,link 变成红色
  • 直接写样式
<li><Link to="/about" activeStyle={{ color: 'red' }}>About</Link></li>
  • 通过className
<li><Link to="/about" activeClassName="active">About</Link></li>
// index.html
<link rel="stylesheet" href="index.css" />
.active {
  color: green;
}

link 效果封装成组件

  • 组件中
<Link {...this.props} activeClassName="active"/>
  • 组件调用
<NavLink to="/about">About</NavLink>

添加变量到路由

  • 链接
<Link to="/repos/reactjs/react-router">React Router</Link>
  • 传递给组件的
{this.props.params.repoName}

添加默认页

{this.props.children || <Home/>}

或者

<Router history={hashHistory}>
    <Route path="/" component={App}>
      {/* add it here, as a child of `/` */}
      <IndexRoute component={Home}/>
      <Route path="/repos" component={Repos}>
        <Route path="/repos/:userName/:repoName" component={Repo}/>
      </Route>
      <Route path="/about" component={About}/>
    </Route>
</Router>

为默认页添加导航

  • 如下这样改,点击任何的,home都是active状态
<li><NavLink to="/">Home</NavLink></li>
  • 如下修改,就不这样了,但是选中子导航,父导航也是active状态
// App.js
import { IndexLink } from 'react-router'

// ...
<li><IndexLink to="/" activeClassName="active">Home</IndexLink></li>
  • 如下修改,选中子导航,父导航不是active状态
<li><Link to="/" activeClassName="active" onlyActiveOnIndex={true}>Home</Link></li>

browserHistory 和 hashHistory

posted @ 2017-03-15 13:21  Meow-z  阅读(178)  评论(0编辑  收藏  举报