我有问题)
我有路由器
<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}
???
最佳答案
- 您可以使用 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>
- 如果 I18n 组件是提供者,您应该使用它来包装根树(在 create-react-app 样板的 app.js 中)。 在每个路由组件(例如 HomeView)中,实现一个将位置更新到状态管理中的功能。
关于javascript - React Router 如何使用 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50511120/