如何使用react-router通过路由将props传递给react组件?

IT技术 reactjs react-router react-redux
2021-05-04 23:28:00

我想将一些props传递给 IndexRoute 上的组件。下面是我的代码片段:

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

在初始加载时,我可以将 step1 作为子项加载,但我想将一些props从路由部分传递到组件。

我怎样才能得到这个?

请指导我。

谢谢,维杰

3个回答

使用克隆元素 cloneWithProps()

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

并将其传递给 <IndexRoute />

<IndexRoute component={newStep1} />

这应该工作..

参考

在您的应用程序中而不是children添加以下行:

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

那应该有效。

您可以Route像这样简单地通过对象添加它们

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

然后在Step1组件中,您可以props再次通过

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