reactjs - React + Typescript : copying props of a custom component - React. PropsWithoutRef 对我不起作用

标签 reactjs typescript

我有一个包装 Router 的组件并需要额外的 Prop 。我尝试使用 PropsWithoutRef以类似于 this cheatsheet 中的使用方式:

import React, { ComponentType, PropsWithoutRef } from 'react'
import { Route } from 'react-router'

type LayoutRouteProps = PropsWithoutRef<Route> & {
    component: ComponentType,
};


const DashboardLayoutRoute = ({
    component: Component,
    ...rest
}: LayoutRouteProps) => {
    const render = (props: any)=> <Component {...props} />

    return <Route {...rest} render={render} />
};

但这并没有什么好处。当我尝试使用 DashboardLayoutRoute并传递与 Route 相关的 Prop :
<DashboardLayoutRoute exact path='/' component={Home} />

我得到

Error:(63, 39) TS2322: Type '{ exact: true; path: string; component: any; }' is not assignable to type 'IntrinsicAttributes & Route & { component: ComponentType<{}>; }'.

Property 'exact' does not exist on type 'IntrinsicAttributes & Route & { component: ComponentType<{}>; }'.



错误:(66, 39) TS2322: 输入 '{ path: string;组件:任何; }' 不可分配给类型 'IntrinsicAttributes & Route & { component: ComponentType<{}>; }'。

Property 'path' does not exist on type 'IntrinsicAttributes & Route & { component: ComponentType<{}>; }'.



我的代码有什么问题?

最佳答案

进一步找到解决方案 in the same cheatsheet !

从组件中提取 props 的正确方法不是通过 PropsWithoutRef但通过 React.ComponentProps (或 React.ComponentPropsWithoutRef)与 typeof 结合使用:

import React, { ComponentType, ComponentProps } from 'react'
import { Route } from 'react-router'

type LayoutRouteProps = ComponentProps<typeof Route> & {
    component: ComponentType,
};

但正如 Mor Shemesh 在他的回答中指出的那样,最好在可以时导入类型:
import React, { ComponentType } from 'react'
import { Route, RouteProps } from 'react-router'


type LayoutRouteProps = RouterProps & {
    component: ComponentType,
};

关于reactjs - React + Typescript : copying props of a custom component - React. PropsWithoutRef 对我不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59136968/

相关文章:

reactjs - 将错误响应拦截器放在 redux-axios-middleware 上

javascript - 如何连接 Material 表中的两个或多个字段 react

angular - 如何在 Angular2 中使用 Observable 通过 id 查找数组元素

javascript - 提前编译时出现 SystemJS 错误(NgZone 没有提供程序)

typescript - Vue 3 兄弟组件通信

javascript - React 如何区分具有相同父级的两个数组的相似键?

javascript - ReactJS AJAX 最佳实践

twitter-bootstrap - 如何使用 React-Router 处理 React-Bootstrap 的 Nav NavItem 中的 .active 状态

typescript - 递归函数中的基本情况不会停止递归 typescript

angular - 错误错误 : Uncaught (in promise): invalid link: LoginPage