简体   繁体   English

React Router如何使用道具?

[英]React Router how use props?

i have question) 我有问题)

I have router 我有路由器

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

......

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

I need in all component get {this.props.match.parameters} and transfer to Another Component for example: 我需要在所有组件中获取{this.props.match.parameters}并转移到另一个组件,例如:

return (

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

)

There are many components i have and each components i must wrap to I18n component. 我有许多组件,每个组件都必须包装到I18n组件。 It is not conveniently. 这不方便。 Can i wrap one times all components to I18n and in I18n grab {this.props.match.paraments} ??? 我是否可以将所有组件包装一次到I18n并在I18n中抢{this.props.match.paraments}

  1. You can use HOC to create a function Example: 您可以使用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. If I18n component is provider, you should use it to wrap in root tree (in app.js of create-react-app boilerplate). 如果I18n组件是提供程序,则应使用它包装在根树中(在create-react-app样板的app.js中)。 In each route component as HomeView, implement a function to update location into state management. 在作为HomeView的每个路由组件中,实现将位置更新为状态管理的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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