2016-03-08 91 views
1

我正在使用react-router 1.0.2。我有一個表示產品目錄的組件目錄,我不想爲每個不同的產品編寫不同的目錄,而是重新使用現有的產品目錄,並將路由器中的productType作爲prop傳遞。我該如何用這個版本的react-router來做到這一點?到目前爲止,我已經試過這個沒有成功...謝謝將道具傳遞給組件react-router 1.0.x

ReactDOM.render(
<Provider store={store}> 
    <Router history={history}> 
     <Route path="/" component={App}> 
      <IndexRoute component={Home}/> 

      <Route path="phones" component={Catalog} productType="phones"/> 
      <Route path="about" component={About}/> 
      <Route path="login" component={Login}/> 

     </Route> 
    </Router> 
</Provider>, 
document.getElementById('main') 

);

回答

2

我會離開你的路線儘可能通用,這是我認爲你想要實現的。爲此,您可以從Catalog組件中查看當前路徑,並根據它的內容呈現不同的子元素。假設您有一個Product組件,您可以將產品類型傳遞給該組件。

所以,如果你有路線:

<Route path="catalog/:productType" component={Catalog}/> 

你可以這樣做:

class Catalog extends React.Component { 
    render() { 
     let productType = this.props.params.productType; 

     return (
      <div className="catalog"> 
       <Product type={productType}/> 
      </div> 
     ); 
    } 
} 
+0

啊,所以你的建議把它作爲網址PARAM而不是道具。優雅。我喜歡。謝謝 – fgonzalez

+0

很高興我可以幫助:) –