2016-03-08 70 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

很高兴我可以帮助:) –

相关问题