如何通过Props传递参数给react-router-dom的Link组件实现正确跳转?
问题描述
我有6个Post组件,希望点击每个组件跳转到不同的链接。当前Posts组件代码如下:
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的Post组件时,会跳转到http://localhost:3000/post/%7Bredirect%7D;尝试过通过state传递参数:
<Link to={{ pathname: "/post", state: { redirect } }} className="link" > {title} </Link>
但同样无效。希望实现点击<Post title="2BHK 2Bath" rent="20000" redirect="1" />时,跳转到http://localhost:3000/post/1。
解决方案
问题核心是字符串拼接方式错误,"/post/{redirect}"是固定字符串,不会解析变量值。需要使用模板字符串来动态生成路径:
- 修改Post组件中的Link代码:
<Link to={`/post/${redirect}`} className="link" > {title} </Link>
- 确保路由配置中存在对应的动态路由规则(以React Router v6为例):
// 在路由配置文件中添加 <Route path="/post/:id" element={<PostDetail />} />
- 若需要在目标页面获取该参数,在
PostDetail组件中使用useParams()钩子:
import { useParams } from 'react-router-dom'; function PostDetail() { const { id } = useParams(); // id即为传递的redirect值,如1、2等 return <div>房源编号:{id}</div>; }
内容的提问来源于stack exchange,提问作者alex deralu
相关产品推荐
相关产品推荐

