简体   繁体   中英

Pass props to components react-router 1.0.x

I'm using react-router 1.0.2. I have a component Catalog representing a catalog of products, I don't want to write a different Catalog for each different product but to reuse the existing one and to pass the productType as prop from the router. How am I supposed to do it with this version of react-router? So far I have tried this without sucess... Thank you

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')

);

I would leave your routes as generic as possible, which is what I think you're trying to achieve. To do this, you could look at the current path from within your Catalog component and depending on what it is, render a different child element. Suppose you have a Product component, you could pass the product type to that.

So if you had route:

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

You could do this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM