我的工作应用程序中有很多不同的链接。我正在创建的最新版本是技术登录路线,该路线将允许他们登录并更新其个人资料。我想让导航栏停留在主页上,同时在子路径之间切换而不必再次渲染它,所以我在网上看了一下,看来嵌套路径是解决此问题的方法。问题是我无法将Route Children
嵌套在Route Component
内。因此,我发现对于React Router
,您可以仅将Component
本身用作路由。我的主要问题是,如果我不能使用Route Component
,如何为该组件的路由设置路径?
这是我的Index.js中的内容:
ReactDOM.render((
<BrowserRouter>
<Switch>
<Route exact path='/' component={App}/>
<Route path='/service' component={ServiceReport} />
<Route exact path='/inventory' component={InventorySystem} />
<Route path='/inventory/tracking' component={PartTracker} />
<Route path='/inventory/build-assembly' component={BuildAssembly} />
<Route path='/inventory/import-purchase-order' component={ImportPO} />
<Route path='/inventory/update-item' component={UpdateItem} />
<Route path='/inventory/create-item' component={CreateItem} />
<Route path='/inventory/receive-items' component={ReceiveItem} />
<TechPortalHome>
<Route path='page1' component={Page1} />
<Route path='page2' component={Page2} />
</TechPortalHome>
</Switch>
</BrowserRouter>), document.getElementById('appRoot'));
如果我输入mysite/anythingelse
,它将渲染TechPortalHome Component
,因为它没有实际路径。由于没有路径匹配,因此它将呈现该组件。我希望能够转到mysite/tech-home
并使其呈现此组件,但是我不确定如何做到这一点。任何帮助将不胜感激,谢谢!
答案 0 :(得分:0)
请检查以下示例:
export default function NestingExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
<hr />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/topics">
<Topics />
</Route>
</Switch>
</div>
</Router>
);
}
function Home() {
return (
<div>
<h2>Home</h2>
</div>
);
}
function Topics() {
// The `path` lets us build <Route> paths that are
// relative to the parent route, while the `url` lets
// us build relative links.
let { path, url } = useRouteMatch();
return (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${url}/rendering`}>Rendering with React</Link>
</li>
<li>
<Link to={`${url}/components`}>Components</Link>
</li>
<li>
<Link to={`${url}/props-v-state`}>Props v. State</Link>
</li>
</ul>
<Switch>
<Route exact path={path}>
<h3>Please select a topic.</h3>
</Route>
<Route path={`${path}/:topicId`}>
<Topic />
</Route>
</Switch>
</div>
);
}
function Topic() {
// The <Route> that rendered this component has a
// path of `/topics/:topicId`. The `:topicId` portion
// of the URL indicates a placeholder that we can
// get from `useParams()`.
let { topicId } = useParams();
return (
<div>
<h3>{topicId}</h3>
</div>
);
}