基于TypeScript的React应用中如何给带参数的Route传递额外props
解决方案(适配你当前使用的react-router v5版本)
步骤1:修改Route组件的渲染方式
不要使用component属性挂载组件,改用render回调属性,该回调可以接收路由原生props,你可以在此处将原生props和自定义props同时传递给目标组件,不会触发不必要的组件卸载重挂载:
<Route path="/client/:id" render={(routeProps) => <Client {...routeProps} clientHeaderText="你要传递的头部文本" />} />
此处的routeProps就包含了你需要的match、location、history三个路由原生属性,展开传递后不会影响原有路由属性的正常使用。
步骤2:修改Client组件的类型定义
扩展原有的props类型,追加你要传递的自定义属性声明:
import { RouteComponentProps } from "react-router"; type TParams = { id: string }; // 组合路由原生props和自定义props type TClientProps = RouteComponentProps<TParams> & { clientHeaderText: string; }; const Client: React.SFC<TClientProps> = (props) => { return ( <> {/* 可以正常使用自定义prop */} <h1>{props.clientHeaderText}</h1> <h2>This is the id route parameter :{props.match.params.id}</h2> </> ); }; export default Client;
内容的提问来源于stack exchange,提问作者doDDy
相关产品推荐
相关产品推荐

