import React from 'react'import { Router, Route, Link } from 'react-router' const App =React.createClass({ render() { return( <div> <h1>App</h1> <ul> <li><Link to="/about">About</Link></li> <li><Link to="/inbox">Inbox</Link></li> </ul>{this.props.children} </div>) } }) const About =React.createClass({ render() { return <h3>About</h3>} }) const Inbox =React.createClass({ render() { return( <div> <h2>Inbox</h2>{this.props.children || "Welcome to your Inbox"} </div>) } }) const Message =React.createClass({ render() { return <h3>Message {this.props.params.id}</h3>} }) React.render(( <Router> <Route path="/" component={App}> <Route path="about" component={About} /> <Route path="inbox" component={Inbox}> <Route path="messages/:id" component={Message} /> </Route> </Route> </Router>), document.body) this.props.location.query.bar和this.props.match,params.id效果一样
路由的嵌套使用
想象一下当 URL 为 / 时,我们想渲染一个在 App 中的组件。不过在此时,App 的 render 中的 this.props.children 还是 undefined。
这种情况我们可以使用 IndexRoute 来设置一个默认页面。 import { IndexRoute } from 'react-router' const Dashboard =React.createClass({ render() { return <div>Welcome to the app!</div>} }) React.render(( <Router> <Route path="/" component={App}>{/*当 url 为/时渲染 Dashboard */} <IndexRoute component={Dashboard} /> <Route path="about" component={About} /> <Route path="inbox" component={Inbox}> <Route path="messages/:id" component={Message} /> </Route> </Route> </Router>), document.body)
现在,App 的 render 中的 this.props.children 将会是 <Dashboard>这个元素。
这个功能类似 Apache 的DirectoryIndex 以及 nginx的 index指令,上述功能都是在当请求的 URL 匹配某个目录时,允许你制定一个类似index.html的入口文件。 我们的 sitemap 现在看起来如下: URL 组件 / App ->Dashboard /about App ->About /inbox App ->Inbox /inbox/messages/:id App -> Inbox -> Message