首页 > 解决方案 > React 和 typescript ReactRouterProps 问题

问题描述

我需要解构我的通用道具并匹配(从 URL中获取“id” )。

组件(使用道具):

interface Props  extends RouteComponentProps<{id: string}>{
  initialProjectName: string;
  workspaceId: string;
}

const AddResources: React.FC<Props> = ({
  initialProjectName,
  workspaceId,
  match,
}) => {
  const projectId = match.params.id; // used here without any error

但是当我传递道具时父组件显示错误

家长

<div>
      <h1>Start Project Page</h1>
      <AddResources
        initialProjectName={initialProjectName}
        workspaceId={workspaceId}   // error
      />
    </div>

错误信息

在此处输入图像描述

标签: javascriptnode.jsreactjstypescriptreact-router

解决方案


通过使用RouteComponentProps,您可以指定您的组件需要路由道具,但您还需要确保传递这些道具。如果组件直接位于 a 下方Route(即作为子组件或通过 using <Route component={..}/>,则路由 props 会自动传递,如果不是,您可以使用withRouter( docs ) 获取它们:

const AddResourcesWithRouter = withRouter(AddResources);

并使用AddResourcesWithRouteris而不是AddResources.


推荐阅读