reactjs - 如何在基于 Typescript 的 React Web 应用程序中具有参数的 Route 元素中传递其他道具
问题描述
我在 React 中有一个功能组件,其中定义了一个带有一些路由的 Switch 组件。我想在其中一个路由(也有参数)中传递额外的道具,以便在有人访问路由时我将安装的组件中使用它。
例如,这是路线。
<Route path="/client/:id" component={Client} />
我希望能够在这个组件中传递一些我们需要的额外道具。我们还需要在客户端组件中使用 Location、matches 和 history 属性。例如,我们需要传递一个 (clientHeaderText :string)
道具。
客户端组件:
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
道具并通过路由道具和任何其他道具。
<Route
path="/client/:id"
render={routeProps => <Client {...routeProps} clientHeaderText="....." />}
/>
您可能需要将新clientHeaderText
道具添加到您的类型定义中,并与路由道具类型合并。