Sth*_*Sth 5 html javascript css reactjs react-router
我有这样的 HTML 结构:
<body>
<nav>
<!--navigation elements -->
</nav>
<div className='main'>
<!--other elements -->
</div>
<div className='container'></div>
</body>
Run Code Online (Sandbox Code Playgroud)
路由定义如下:
<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>
Run Code Online (Sandbox Code Playgroud)
“容器”元素存在于所有路由上,但我不希望它在“/”路由上呈现。
我怎样才能停止<div className="container">在"/"路线上被渲染?我希望它在除"/".
我发现但不想使用的解决方案class="container"是在我的<Switch>. 有没有更好的办法?
You should be able to achieve what you require via nested routes and a "no match route".
The idea would be to introduce structure to your routing via nested routes, to restrict rendering of <div className="container"> to non / routes.
To do this, you could extract a component (ie WithContainer) that renders a <Route> for paths; /register, /login and /profiles, inside of the <div className="container">. You would then change your <Switch> to now render two routes for the following route cases;
<Route/> that renders the Landing component on an exact match of /<Route/> that renders your new WithContainer component on no specific route (ie any path that does not exactly match /)通过<Switch>以这种方式使用 ,它会导致路由行为根据第一个匹配的路由呈现Landing或WithContainer(但不是两者)。我们利用这种行为来限制“非”路由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>
)
Run Code Online (Sandbox Code Playgroud)
希望有帮助!
| 归档时间: |
|
| 查看次数: |
4033 次 |
| 最近记录: |