首页 > 解决方案 > React Router如何使用props?

问题描述

我有问题)

我有路由器

<Switch>
<Route exact path={`/:lng(en|ru)?`} component={HomeView} />

......

<Route component={NotFoundView} />
</Switch>

我需要在所有组件中获取{this.props.match.parameters}并转移到另一个组件,例如:

return (

    <I18n lang={this.props.match.paraments}>
                .....
    </I18n>

)

我有很多组件,每个组件都必须包装到 I18n 组件。这不方便。我可以将所有组件包装一次到 I18n 并在 I18n 中抓取吗{this.props.match.paraments}

标签: javascriptreactjsreact-routerreact-redux

解决方案


  1. 您可以使用 HOC 创建函数示例:

function withI18n(Comp, lang){
      return class I18nWrapper extends React.Component{
       ...
       
        render(){
          return(
            <I18n lang={lang}>
              <Comp {...props}/>
            </I18n>
          );
        }
      }
    }
    
// And in Router, you can use withI18n Hoc with render propery of Route component

<Switch>
    <Route exact path={`/:lng(en|ru)?`}
    render={(location, match, history) => {
     return withI18n(HomeView, match.path)
    }}

    ......

    <Route component={NotFoundView} />
    </Switch>

  1. 如果 I18n 组件是提供者,您应该使用它来包装根树(在 create-react-app 样板的 app.js 中)。在作为 HomeView 的每个路由组件中,实现一个将位置更新为状态管理的功能。

推荐阅读