英文:
React insert component inside of the parent Route's component
问题
我正在开发一个用React制作的论坛作为练习。我有以下的路由结构(不完整,伪代码)
<Routes>
// 固定的工具栏
<Route index element={<Toolbar />}>
// 查看帖子中的所有主题
<Route path="thread/:threadId" element={<ThreadItem />} />
</Route>
</Routes>
在我的ThreadItem组件中,它显示了主题中的帖子,我想在Toolbar组件中插入分页链接。
是否可以将一个组件的内容插入到另一个组件中?是否可以使用Portals?这样做是否干净?
英文:
I'm developing a forum in react as an exercise. I have the following Route structure(not complete, pseudocode)
<Routes>
//fixed Toolbar
<Route index element={<Toolbar />}>
//view of all the threads in the post
<Route path="thread/:threadId" element={<ThreadItem />} />
</Route>
</Routes>
In my ThreadItem component, which displays the posts in the thread, I want to insert pagination links into the Toolbar component.
Is it possible to insert content from one component into another component? Does It work with Portals? Is it clean?
答案1
得分: 0
你可以在你的 <Toolbar />
内部使用 useLocation
钩子来获取当前活动的路由。
如果活动路由与你的 :threadId
路由匹配,就渲染分页链接。
类似这样的代码可以满足你的需求:
import { useLocation, matchPath } from "react-router-dom";
const location = useLocation();
const pagination = matchPath('要匹配的路径', location.pathname) && (<PaginationLinks />);
英文:
You could use the useLocation
hook inside your <Toolbar />
to get the currently active route.
If the active route matches your :threadId
route, render the pagination links.
Something like this could fit your needs
import { useLocation , matchPath } from "react-router-dom";
const location = useLocation();
const pagination = (matchPath('your-path-to-match', location.pathname))
&& (<PaginationLinks />);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论