我有一个包装 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/