使用react-router-dom
‘S嵌套管线是否会迫使您渲染嵌套管线组件within父管线组件?我对航线是新手,我正在努力理解.
我有一个下面模拟的Reaction应用程序,我在开发过程中引入了react-router-dom
V6.ComponentView
根据标题props 渲染所需的组件.我已经设置了如下路由,其中"/a"
和"/b"
被映射到根据标题值呈现的ComponentView
组件.我想要的是在不更改组件 struct 的情况下使"/b"
成为"/a"
的嵌套路由.这有可能吗?
我试着像这样重组航线:
<Route path="a" element={<ComponentView title="a" />}>
<Route path="b" element={<ComponentView title="b" />} />
</Route>
...但如果我导航到"/a/b"
,我得到的相当于"/a"
.
到目前为止,根据我对Reaction路由的了解,如果我想让"/b"
成为"/a"
的子集,这意味着在"/b"
中呈现的组件将呈现in addition to,无论组件(S)由"/a"
呈现.有没有办法在不嵌套内容的情况下嵌套路径?
App.js
import React from "react";
import { Route, Routes } from 'react-router-dom';
import './App.css';
import { Home } from "./components/Home"
import { ComponentView } from "./components/ComponentView";
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Home />} />
<Route path="a" element={<ComponentView title="a" />} />
<Route path="b" element={<ComponentView title="b" />} />
</Routes>
</div>
);
}
export default App;
ComponentView.js
import { ComponentA } from "./ComponentA";
import { ComponentB } from "./ComponentB";
export function ComponentView(props) {
return (
<div>
{props.title === "a" ? (
<ComponentA title={props.title} />
) : (
<ComponentB title={props.title} />
)}
</div>
);
}
ComponentA.js
export function ComponentA(props) {
return(
<div>
<div style={{ height: "5rem", width: "100%" }}>
Component A - title: {props.title}
</div>
</div>
);
}
ComponentB.js
export function ComponentB(props) {
return(
<div>
<div style={{ height: "5rem", width: "100%" }}>
Component B - title: {props.title}
</div>
</div>
);
}