React Router:如何在所有路由上渲染元素,除了一个?



我有这样的HTML结构:

<body>
<nav>
<!--navigation elements -->
</nav>
<div className='main'>
<!--other elements -->
</div>
<div className='container'></div>
</body>

路由定义如下:

<Router>
<Fragment>
<Navbar />
<Route exact path="/" component={Landing} />
<div className="container">
<Alert />
<Switch>
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={Login} />
<Route exact path="/profiles" component={Profiles} />
</Switch>
</div>
</Fragment>
</Router>
">

容器"元素存在于所有路由上,但我不希望它在"/"路由上呈现。

如何阻止<div className="container">"/"路由上渲染?我希望它在除"/"以外的所有其他路由上呈现。

我找到但不想使用的解决方案是在<Switch>中呈现的每个组件中显式插入带有class="container"的元素。有没有更好的方法?

您应该能够通过嵌套路由和"不匹配路由"实现所需的目标。

这个想法是通过嵌套路由将结构引入路由,以将<div className="container">呈现限制为非/路由。

为此,您可以提取一个组件(即WithContainer)来呈现路径<Route>;/register/login/profiles,在<div className="container">里面。然后,您将更改<Switch>,现在为以下路径事例渲染两条路径;

  1. 以完全匹配的/呈现Landing组件的<Route/>
  2. 一种<Route/>,它没有特定的路由(即任何与/不完全匹配的路径)上呈现您的新WithContainer
  3. 组件

通过以这种方式使用<Switch>,它会导致路由行为呈现LandingWithContainer(但不是两者),具体取决于第一个匹配的路由。我们利用这种行为来限制"非/"路由的WithContainer(进而<div className="container">元素)的呈现。

在代码中,此方法可以表示为:

const WithContainer = () => (
<div className="container">
{ /* Wrap routes in container div */ }
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={Login} />
<Route exact path="/profiles" component={Profiles} />
</div>)
const Main = () => (
<main> 
<Switch>
<Route exact path='/' component={Landing}/>
<Route component={ WithContainer } /> {/* No match route */ }
</Switch>
</main>
)

希望对您有所帮助!

使用最新版本的 React Router,您可以为pathprop 提供一个字符串数组,以便特定路由在多个匹配项上呈现:

<Route path={['/one', '/two', '/three']} component={SomeComponent} />

以下是相关文档的链接:https://reacttraining.com/react-router/web/api/Route/path-string-string。

如果您不想创建单独的组件,则可以执行此操作。如果要保留原始功能,还需要保留内部开关。

// parent switch
<Switch>
<Route exact path="/" component={Landing} />
// start route wrap!!!
<Route> 
<div className="container">
<Switch>
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={Login} />
<Route exact path="/profiles" component={Profiles} />
</Switch>
</div>
</Route>
// end route wrap!!!
</Switch>

应将路由视为任何其他 UI 组件。您可以任意嵌套它们。

最新更新