咨询react-router-dom的<Link/>组件传递参数的可行方案
关于react-router-dom的Link组件传参问题
嘿,我来帮你理清这个问题~首先得说,你第一种写法<Link to='/meals/new' params='test'>Add Food</Link>没办法直接生效,原因很简单:react-router-dom的Link组件根本不认识params这个自定义属性,你直接把它写在组件上,路由系统完全不会处理这个属性,所以接收方自然拿不到任何参数。
不过别担心,我们可以通过两种方式实现类似第一种写法的简洁传参,同时还能顺利传递组件的props或本地状态:
方式一:自定义封装一个支持直接传参的Link组件
你可以自己写个小组件把原生Link包一层,让它支持直接传入params、title这类自定义属性,内部自动把这些参数放到路由的state里。代码示例如下:
import { Link } from 'react-router-dom'; // 自定义封装的Link组件 const CustomLink = ({ to, params, title, children, ...restProps }) => { // 把字符串路径转换成对象形式,方便合并state const targetPath = typeof to === 'string' ? { pathname: to } : to; return ( <Link to={{ ...targetPath, // 把自定义参数合并到state里,同时保留原有的state(如果有的话) state: { params, title, ...targetPath.state } }} {...restProps} > {children} </Link> ); };
之后你就可以像第一种写法那样简洁地使用了,还能直接传递组件的本地状态:
// 在你的类组件里 render() { return ( <CustomLink to='/meals/new' params='test' title={this.state.title}> Add Food </CustomLink> ); }
方式二:直接使用to对象的state字段(更直接)
其实不需要额外封装,只要把to写成对象形式,并且在组件的render方法里定义(这样就能访问到this.state和this.props了),就能顺利传递参数。比如:
// 类组件的render方法中 render() { return ( <Link to={{ pathname: '/meals/new', // 把需要传递的参数放到state里 state: { params: 'test', title: this.state.title } }} > Add Food </Link> ); }
接收参数的方式
不管用哪种方式传参,目标组件都可以通过路由的location对象获取到参数:
- 如果是类组件,可以通过
this.props.location.state拿到:class MealsNew extends React.Component { componentDidMount() { console.log('传递的参数:', this.props.location.state); // 输出:{ params: 'test', title: '你的状态值' } } } - 如果是函数组件,可以用
useLocation钩子:import { useLocation } from 'react-router-dom'; function MealsNew() { const location = useLocation(); console.log('传递的参数:', location.state); return <div>...</div>; }
内容的提问来源于stack exchange,提问作者peterchic
相关产品推荐
相关产品推荐

