1

React-router

 2 years ago
source link: https://devhints.io/react-router
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Basic

import { default as Router, Route } from 'react-router'

const routes = (
  <Route>
    <Route path='*' handler={RootView} />
  </Route>
)

Router.run(routes, Router.HashLocation, (Root) => {
  React.render(<Root />, document.getElementById('all'))
})

Nesting

const routes = (
  <Route handler={Chrome}>
    <Route path='about' handler={About} />
    <Route path='inbox' handler={Inbox} />
    <Route path='messages/:id' handler={Message} />
  </Route>
)

import { RouteHandler } from 'react-router'

const Chrome = React.createClass({
  render () {
    return (
      <div>
        <h1>App</h1>
        <RouteHandler />
      </div>
    )
  }
})

URL params

var Message = React.createClass({
  componentDidMount: function () {
    // from the path `/inbox/messages/:id`
    var id = this.props.params.id
    ...
import { Link } from 'react-router'

<!-- make a named route `user` -->
<Link to='user' params={{userId: 10}} />

<Link to='login'
  activeClassName='-active'
  onClick='...'>

Other config

<Route path='/'>
  <DefaultRoute handler={Home} />
  <NotFoundRoute handler={NotFound} />
  
  <Redirect from='login' to='sessions/new' />
  <Redirect from='login' to='sessions/new' params={{from: 'home'}} />
  <Redirect from='profile/:id' to='about-user' />

  <Route name='about-user' ... />

Router.create

var router = Router.create({
  routes: <Route>...</Route>,
  location: Router.HistoryLocation
})

router.run((Root) => { ... })

Navigation

import { Navigation } from 'react-router'

React.createClass({
  mixins: [ Navigation ], ...
})

this
  .transitionTo('user', {id: 10})
  .transitionTo('/path')
  .transitionTo('http://...')
  .replaceWith('about')
  .makePath('about') // return URL
  .makeHref('about') // return URL
  .goBack()

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK