如何在基于 Typescript 的 React Web 应用程序中通过具有参数的 Route 元素传递附加道具

How to pass additional props throughout a Route element that has parameters in a Typescript based React Web Application

我在 React 中有一个功能组件,其中定义了一个带有一些路由的开关组件。我想在这些路线之一(也有参数的路线)中传递额外的道具,以便在有人访问路线时我将安装的组件中使用它。

例如,这是路线。

<Route path="/client/:id" component={Client} /> 

我希望能够在此组件中传递一些我们需要的额外道具。我们还需要在客户端组件中使用 Location、matches 和 history 道具。例如,我们需要传递一个 (clientHeaderText :string) prop.

客户端组件:

import { RouteComponentProps } from "react-router";

type TParams = { id: string };

const Client: React.SFC<RouteComponentProps<TParams>> = (props) => {
  return (
    <>
      <h1>This is the id route parameter :{props.match.params.id}</h1>
    </>
  );
};

export default Client;

如何实现此功能?

如果您需要将其他道具传递给路由组件,那么您应该使用 render 道具并通过路由道具 and 任何额外的道具。

<Route
  path="/client/:id"
  render={routeProps => <Client {...routeProps} clientHeaderText="....." />}
/> 

您可能需要将新的 clientHeaderText 道具添加到您的类型定义中,并与路由道具类型合并。

如果你想传递额外的 Props,你可以在你的组件中使用路由器自定义钩子 {useParams, useLocation, useHistory, useRouteMatch}(你可以找到更多关于这个的信息 here)。使用这种方法,您不需要在客户端组件中接收 RouteComponentProps<TParams>,最终代码如下所示。

路由元素:

<Route path="/client/:id" render={() => <Client clientHeaderText={clientHeaderText}/>}/>

客户端组件:

export type ClientProps = { clientHeaderText :string };
const Client: React.SFC<ClientProps> = (props) => {
  const params = useParams<TParams>();
  return (<h1> {props.clientHeaderText} : {params.id} </h1>);
};
export default Client;