簡體   English   中英

當我使用點擊導航時,如何將我的 id 傳遞給文件 SinglePost

[英]How do I pass my id to the file SinglePost when I'm using on click navigate

點擊發生的地方:

<img onClick={() => {navigate("/single")}} className="postImages" src={post.img_url} alt={post.title} />

這是孔組件:

在此處輸入圖像描述

您可以將其作為狀態傳遞(我假設post有一個id字段,如果不是,請隨意更改它):

<img
  onClick={() => navigate("/single", { state: { id: post.id } })}
  className="postImages"
  src={post.img_url}
  alt={post.title}
/>

並借助 React Router Dom 的useLocationSinglePost中獲取它:

// import the hook at the top of the component
import {useLocation} from "react-router-dom";
// use it inside the component
const { state } = useLocation();
console.log(state.id);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM