How to pass props to react component through routi

2019-07-08 10:45发布

问题:

I want to pass some props to component on IndexRoute. Below is my code snippet:

render(root: Element) {
    const { store, params } = this as any;
    ReactDOM.render(
          <Provider {...{ store }} >
              <Router history={browserHistory}>
                  <Route path={window.location.pathname} component={App}>
                    <IndexRoute component={Step1} />
                    <Route path="step1" component={() => (<Step1 params={params} />)} />
                    <Route path="step1" component={() => (<Step2 params={params} />)} />
                  </Route>
            </Router>
          </Provider>
   , root);

}

//App Component
import * as React from 'react';


export var App: any = ({children}) => (

    <div>
        <div>{children}</div>
    </div>
)

On initial load I am able to load step1 as children but I want to pass some props from routing section to component.

How can I get this?

Please guide me.

Thanks, Vijay

回答1:

Clone the elemnt using cloneWithProps()

var newStep1 = cloneWithProps(Step1, {prop1: 'value', prop2: 'value'});// add props

And pass it to <IndexRoute />

<IndexRoute component={newStep1} />

This should work..

Reference



回答2:

In your App instead of children add this line:

{React.cloneElement(children, {params: params})}

That should work.



回答3:

You can simply add them through the Route object like this:

<Route path="step1" someParams={params} component={Step1} />

And then in the Step1 component you can get them through the props again:

render() {
    console.log(this.props.route.someParams);
}