React-Router - Introduction

react-router简单应用

实现多个组件间的切换

分组件

export class About extends React.Component<any, any> {
constructor() {
super();
}

render() {
return (
<div>this is About page</div>
)
}
}
export class Inbox extends React.Component<any, any> {
constructor() {
super();
}

render() {
return (
<div>
<div>this is Inbox page </div>
<div>child routes here: {this.props.children}</div>
</div>

)
}
}
export class Home extends React.Component<any, any> {
constructor() {
super();
}

render() {
return (
<div>this is Home page</div>
)
}
}

根组件

export class App extends React.Component<any, any> {
constructor() {
super();
}
render() {
return (
<div>
<h1>App</h1>
{/* change the <a>s to <Link>s */}
<ul>
<li><Link to="/about">About</Link></li>
<li><Link to="/inbox">Inbox</Link></li>
<li><Link to="/inbox/?aa=xx">Inbox with querystring</Link></li>
<li><Link to="/inbox/messages/123456">messages with id</Link></li>
</ul>

{/*
next we replace `<Child>` with `this.props.children`
the router will figure out the children for us
*/}
{this.props.children}
</div>
)
}
}

内嵌子组件

export class Message extends React.Component<any, any> {
constructor() {
super();
}
render() {
return (
<div>Message{this.props.params.id}</div>
)
}
}

export class NewMessage extends React.Component<any, any> {
constructor() {
super();
}
render() {
return (
<div>New Message{this.props.location.query.aa}</div>
)
}
}

router

// Finally, we render a <Router> with some <Route>s.
// It does all the fancy routing stuff for us.
render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="about" component={About} />
<Route path="inbox" component={Inbox}>
{/* add some nested routes where we want the UI to nest */}
{/* render the stats page when at `/inbox` */}
<IndexRoute component={NewMessage}/>
{/* render the message component at /inbox/messages/123 */}
<Route path="messages/:id" component={Message} />
</Route>
</Route>
</Router>
), document.body)

首先看Router里只包了一个Route App,这个NG2里的routeconfig很像
path xx component xxx

IndexRoute 说的其实就是默认路由
Route 组件里面还可以内嵌其他路径,就是ng2里的子路由概念

当点击messages with id link的时候, 他会一级一级的render 所以会出现 app inbox message

  • message 是一个path里带参数的例子
  • inbox 是一个带queryString的例子
  • 注意 {this.props.children} 相当于routeOutlet