React Router如何向MyComponent传递等效查询参数形式的数据?
嘿,针对你的需求——通过props给MyComponent传递等效于查询参数的数据,我整理了几个实用的方案,适配你现有的路由和ActiveLink组件:
方案1:路由
render方法直接传递静态props 你原来的路由使用component属性无法直接自定义传参,换成render方法就能灵活给MyComponent传递props,完全替代查询参数的效果:
<Route path={'/mycomponent'} exact render={(routeProps) => ( <MyComponent {...routeProps} // 保留路由自带的history、location等props aparam="hello" anotherparam={32} /> )} />
这样MyComponent里直接通过props.aparam和props.anotherparam就能拿到数据,完全符合你优先用props传递的需求,比解析查询参数更直接。
方案2:ActiveLink动态传state,路由转props给组件
如果你的参数是动态的(比如点击ActiveLink时才确定参数值),可以通过路由的state传递数据,再转成props传给组件:
首先修改ActiveLink,让它支持传递state等Link原生属性:
import * as React from 'react' import { Link, LinkProps } from 'react-router-dom' // 扩展原有Props,兼容Link的其他属性(比如state) export interface OwnProps extends Omit<LinkProps, 'to'> { to : string, pathname : string, children : React.ReactChild } const ActiveLink = (props: OwnProps) => { const { pathname, to, children, ...restProps } = props if (pathname === to) { return <span className={'active-link active'}>{ children }</span> } else { // 把state等属性透传给Link组件 return <Link className={'active-link in-active'} to={ to || '/' } {...restProps}>{ children }</Link> } } export default ActiveLink
使用ActiveLink时传入动态参数:
<ActiveLink to="/mycomponent" pathname={location.pathname} state={{ aparam: "hello", anotherparam: 32 }} > 跳转到MyComponent </ActiveLink>
最后修改路由,把location中的state转成props传给MyComponent:
<Route path={'/mycomponent'} exact render={(routeProps) => ( <MyComponent {...routeProps} aparam={routeProps.location.state?.aparam} anotherparam={routeProps.location.state?.anotherparam} /> )} />
这样就能实现点击ActiveLink时动态传参,MyComponent依然通过props接收数据。
补充方案:路径参数转props(可选)
如果你的参数结构固定,也可以把参数放到路由路径中,再通过路由params转成props:
// 修改路由配置 <Route path={'/mycomponent/:aparam/:anotherparam'} exact render={(routeProps) => ( <MyComponent {...routeProps} aparam={routeProps.match.params.aparam} anotherparam={Number(routeProps.match.params.anotherparam)} // 注意类型转换 /> )} />
此时ActiveLink的to需要写成/mycomponent/hello/32,这个方案虽不是直接props传参,但如果你的场景适合路径化参数,也可以作为补充选项。
优先推荐方案1(静态固定参数)或方案2(动态传参),两者都完全通过props传递数据,等效于查询参数的传值效果,且无需手动解析参数。
内容的提问来源于stack exchange,提问作者meds
相关产品推荐
相关产品推荐

