目前我在使用以下代码来运行我的应用程序。
const {
Router,
Route,
IndexRoute,
Redirect,
Link,
IndexLink,
hashHistory
} = ReactRouter
var App = React.createClass({
render : function() {
return (
<div>
<h1>My Application</h1>
<div><Link to="/levelone/1">Go to One</Link></div>
<div><Link to="/levelone/1/leveltwo/5">Go to Three</Link></div>
{this.props.children}
</div>
)
}
})
var Index = React.createClass({
render : function() {
return (
<div>
<h2>This is index route</h2>
</div>
)
}
})
var LevelOne = React.createClass({
render : function() {
return (
<div>
<h2>This is LevelOne</h2>
{this.props.children}
</div>
)
}
})
var LevelTwo = React.createClass({
render : function() {
return (
<div>
<h2>This is LevelTwo</h2>
</div>
)
}
})
var routes= (
<Route path= "/" component={App}>
<IndexRoute component={Index}/>
<Route path="/levelone/:id" component={LevelOne}>
<Route path="/leveltwo/:idd" component={LevelTwo}/>
</Route>
</Route>
)
ReactDOM.render(<Router history={ hashHistory } routes={routes}></Router>, document.getElementById('app'));
<script src="https://unpkg.com/react@15.1.0/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/react-dom@15.1.0/dist/react-dom.js"></script>
<script src="https://npmcdn.com/react-router@3.0.0/umd/ReactRouter.js" charset="utf-8"></script>
<div id="app"><div>
App
链接到 /levelone/1/leveltwo/5
,但此链接无法正常工作,并显示错误[react-router] Location "/levelone/1/leveltwo/5" did not match any routes
。但如果我把链接放在组件
LevelOne
内,就像下面的代码片段一样,链接将指向我想要的LevelTwo。var LevelOne = React.createClass({
render : function() {
return (
<div>
<h2>This is LevelOne</h2>
<div><Link to="leveltwo/5">Go to LevelTwo</Link></div>
{this.props.children}
</div>
)
}
})
如果我想从最外层组件链接到 LevelTwo,应该怎么做?
<Link to="leveltwo/5">Go to LevelTwo</Link>
放在LevelOne
组件内对他有效,而将绝对 URL 放在最外层的App
组件中则无效。当您运行代码片段时可以看到这一点。 - ajaybc