如何捕获父捕获React Rouyter动态参数?

发布于 2025-02-11 12:53:58 字数 256 浏览 1 评论 0原文

我希望能够将孩子的id存储在父组件中。但是,我不确定该怎么做。我知道我可以在孩子中调用useParams(),然后将id传递给父母,但这似乎是一种完成此操作的回旋方式。

<Route path="/project/:id" element={<Child />}>
</Route>

const childId = ???

I want to be able to store the child's id in the parent component. However, I'm not sure how to do so. I know that I can call useParams() in the child, and then pass the id back to the parent, but this seems like a roundabout way to accomplish this.

<Route path="/project/:id" element={<Child />}>
</Route>

const childId = ???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮光之海 2025-02-18 12:53:58

您可以在父组件中创建一个状态,然后在接收ID之后,使用USEPARAMS()将SetState发送到子女组件中,并在子组件中调用SetState;

父母的

const [id, setId] = useState('');
<Route path="/project/:id" element={<Child setId={setId} />}>
</Route>

孩子

const {id} = useParams();
props.setId(id); // Or however you access props in your component

You can create a state in a parent component, then send setState to the child and call setState in child component, after receiving id, using useParams();

Parent

const [id, setId] = useState('');
<Route path="/project/:id" element={<Child setId={setId} />}>
</Route>

Child

const {id} = useParams();
props.setId(id); // Or however you access props in your component
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文