我正在使用react-router,我想在用户不在根目录而不在/ login路径中时呈现菜单组件.这就是我到目前为止所拥有的
<Route path="/:subpath" component={TopMenuComponent} />
<div>
<Route
exact path="/"
render={props => (
<LoginContainer {...props} setTitle={this.setTitle} />
)}
/>
<Route path='/landing' component={LandingComponent} />
</div>
Run Code Online (Sandbox Code Playgroud)
负责不在'/'位置渲染TopMenuComponent组件,但是当用户在/ login路径中时,如何避免它渲染TopMenuComponent?我总是可以创建另一个组件并将其包装起来,但我认为这对此来说太过分了.
路由路径中的正则表达式对我不起作用。对我有用的是这个。只需添加其他条件。
<Route render={({ location }) => {
return location.pathname.indexOf('/login') === -1 ? TopMenuComponent : null
}} />
Run Code Online (Sandbox Code Playgroud)
如果您不想直接使用正则表达式,您可以将您的登录名Route放在Switch带有顶部菜单组件的 a 中Route。它只会运行第一个匹配Route和没有路径属性匹配任何内容的路由。
<div>
<Switch>
<Route
exact path="/"
render={props => (
<LoginContainer {...props} setTitle={this.setTitle} />
)}
/>
<Route path="/:subpath" component={TopMenuComponent} />
</Switch>
<Route path='/landing' component={LandingComponent} />
</div>
Run Code Online (Sandbox Code Playgroud)
对于您的示例,您需要重新排序您的 div。
React Router的匹配path strings依赖于path-to-regexp@^1.7.0。
结果,您可以使用指示routes不渲染某些路径regular expressions。
下面的实现renders在所有paths,酒吧"/"和"/login":
<Route path="^(?!.*(/|/login)).*$" component={TopMenuComponent}/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5451 次 |
| 最近记录: |