javascript - 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}
?
解决方案
- 您可以使用 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 的每个路由组件中,实现一个将位置更新为状态管理的功能。
推荐阅读
- r - RJDBC:获取插入的行数
- node.js - 使用 NodeJS 随时获取 Req 和 Res 变量
- ios - UICustomview 中的触摸事件不起作用 - UICustomview
- reactjs - ReactJS 网页字体
- amazon-web-services - AWS Cloudformation 每次堆栈更新和创建运行一次命令
- c++ - vector.resize() 中的错误分配
- python - 您建议使用哪种分类模型来预测信用评分?
- google-app-engine - 如何将我的域映射到 Google Cloud Shell 的预览服务器 (...-dot-devshell.appspot.com)
- r - 根据 2 个条件将一列拆分为多列
- javascript - JavaScript Datatable.JS / PHP MySQLi 排序问题