如何通过道具传递react路由器dom链接userid



我有六个组件,我想重定向到六个不同的链接

import Post from "../post/Post";
import ".//posts.css";
export default function Posts() {
return (
<div className="flex-container">
<Post title="2BHK 2Bath" rent="20000" redirect="1" />
<Post title="3BHK 2Bath" rent="25000" redirect="2" />
<Post title="1BHK 1Bath" rent="14000" redirect="3" />
<Post title="3BHK 3Bath" rent="30000" redirect="4" />
<Post title="2BHK 2Bath" rent="18000" redirect="5" />
<Post title="1BHK 1Bath" rent="10000" redirect="6" />
</div>
);
}

Post.jsx


export default function Post({ title, rent, redirect }) {
return (
<div className="post">
<img
className="postImg"
src="https://www.thespruce.com/thmb/aGEhef5NbpY6R_Fahn5fIW8SAHk=/941x0/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/put-together-a-perfect-guest-room-1976987-hero-223e3e8f697e4b13b62ad4fe898d492d.jpg"
alt=""
/>
<div className="postInfo">
<div className="postCats"></div>
<span className="postTitle">
<Link
to={{ pathname: "/post/{redirect}" }}
className="link"
>
{title}
</Link>
</span>
<hr />
<span className="postDate">Rent: {rent}/-</span>
</div>
</div>
);
}

这不起作用,点击带有redirect: 1的第一篇帖子会将我重定向到此URLhttp://localhost:3000/post/%7Bredirect%7D

我也试着用堆叠式的来做这个

<Link
to={{ pathname: "/post", state: { redirect } }}
className="link"
>
{title}
</Link>

但这也没有奏效。

我如何做到这一点,我可以通过组件的道具传递redirect_id。

示例:

当我点击<Post title="2BHK 2Bath" rent="20000" redirect="1" />的组件时,它应该会将我重定向到http://localhost:3000/post/1

我该怎么做?

您可以尝试使用模板字符串

<Link to={{ pathname: `/post/${redirect || 0}` }} className="link">  
{title}
</Link>

相关内容

最新更新