2017-02-15 188 views
0

努力讓React-Router爲SPA工作,但我似乎無法讓它呈現除App組件之外的任何東西。ReactJS路由器不路由

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { Router, Route, Link, IndexRoute, browserHistory } from 'react-router'; 
import Parameter from './components/parameter/Parameter'; 

class App extends React.Component { 

    constructor(props) { 
     super(props); 
    } 

    render() { 
     return (
      <div className="container"> 
       <h1>TEST</h1> 
       <Link to="/parameter">Click Me!</Link> 
      </div> 
     ) 
    } 
} 

class Test extends React.Component { 
    render() { 
     return (
      <div className="container"> 
       <h1>TEST PAGE</h1> 
      </div> 
     ) 
    } 
} 

var routes = (
    <Route name="root" component={App} path="/"> 
     <Route component={Test} path="test" /> 
     <Route component={Parameter} path="parameter" /> 
    </Route> 
) 

ReactDOM.render((
    <Router history={browserHistory} routes={routes} /> 
), document.getElementById('react')) 
+0

什麼版本的react-router? –

+0

「react-router」:「^ 3.0.2」 – greyfox

+0

您是否嘗試爲'/ test'和'/ parameter'添加'/'? –

回答

2

你沒有指定你想要的嵌套組件的App組件中呈現。 App組件的行爲類似於所有嵌套路由的佈局。

爲特定路線命中時,您爲嵌套路線指定的組件需要放置在佈局/父組件內的位置。

最簡單的方法是使用{this.props.children}App組件中的某個地方。參考下面的例子。

這裏又是你的應用程序組件:

class App extends React.Component { 
    constructor(props) { 
     super(props); 
    } 

    render() { 
     return (
      <div className="container"> 
       <h1>TEST</h1> 
       <Link to="/parameter">Click Me!</Link> 
       {this.props.children} 
      </div> 
     ) 
    } 
} 

爲了更深入的例子,從反應路由器回購指active-links例子。在他們的示例中,您可以看到children作爲App組件中的道具可用,並且會在命中相關路由時呈現嵌套路由中的任何其他組件。例如,點擊/路由將呈現App內的Index組件,其中{children}被定位,因爲存在直接嵌套的路由<IndexRoute ... />

React提供this.props.children作爲訪問組件子項的方法。它允許您將組件作爲數據傳遞給其他組件。在這種情況下,在App組件內渲染子組件。

0

如果您使用的陣營路由器V4,我覺得嵌套組件不渲染的原因是因爲你可以在不窩<Route />小號陣營路由器V4。

我打開了一個問題,在這個早期:

How to nest routes in React Router v4?

+0

我正在使用React Router 3 – greyfox