[英]React Render Multiple Route elements in single Routes element
I cant seem to render multiple Route elements in a single Routes element.我似乎无法在单个 Routes 元素中呈现多个 Route 元素。 I would like to have a multiple Route elements in a single Routes element since they are both updated dynamically.我想在单个 Routes 元素中有多个 Route 元素,因为它们都是动态更新的。 Does the old syntax/style not work?旧的语法/样式不起作用吗?
Code example:代码示例:
import React from 'react';
import './App.css';
import Header from './Header';
import Home from './Home';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
function App() {
return (
// use BEM naming convention
<Router>
<div className="app">
<Routes>
{/* This one works */}
{/* <Route path="/" element={<><Header /><Home /></>} /> */}
{/* But this doesnt: */}
<Route path="/" element={<Header />} />
<Route path="/" element={<Home />} />
</Routes>
</div>
</Router>
);
}
export default App;
There should be only one Route
per path you want to match.每个要匹配的路径应该只有一个Route
。 In react-router-dom@6
all routes are exclusively matched, the Routes
component serves a similar purpose to, and is the spiritual successor of, the RRDv5 Switch
component.在react-router-dom@6
中,所有路由都是唯一匹配的, Routes
组件的用途与 RRDv5 Switch 组件类似,并且是 RRDv5 Switch
组件的精神继承者。
If you are trying to render common UI logic/components then the recommended way is to use what are called Layout Routes that renders the common logic/UI and an Outlet
component for nested Route
components to render their element
into.如果您尝试渲染通用 UI 逻辑/组件,那么推荐的方法是使用所谓的布局路由来渲染通用逻辑/UI,并使用Outlet
组件来渲染嵌套Route
组件的element
。
If you want to render a Header
component on specific routes then create a layout component that renders the Header
and Outlet
and wrap the routes you want to render with Header
.如果要在特定路由上渲染Header
组件,则创建一个布局组件来渲染Header
和Outlet
并用Header
包装要渲染的路由。
Example:例子:
import { Outlet } from 'react-router-dom';
import Header from '../path/to/Header';
const HeaderLayout = () => (
<>
<Header />
<Outlet /> // <-- nested routes render content here
</>
);
export default HeaderLayout;
... ...
import React from 'react';
import './App.css';
import HeaderLayout from './HeaderLayout';
import Home from './Home';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
function App() {
return (
// use BEM naming convention
<Router>
<div className="app">
<Routes>
<Route element={<HeaderLayout />}>
<Route path="/" element={<Home />} /> // <-- nested route
... other routes with Header
</Route>
... other routes w/o Header
</Routes>
</div>
</Router>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.