【问题标题】:React + Typescript: copying props of a custom component - React.PropsWithoutRef doesn't work for meReact + Typescript:复制自定义组件的道具 - React.PropsWithoutRef 对我不起作用
【发布时间】:2023-03-26 18:21:01
【问题描述】:

我有一个包装 Router 的组件并采用额外的道具。我尝试以类似于this cheatsheet 的方式使用PropsWithoutRef

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 相关的道具时:

<DashboardLayoutRoute exact path='/' component={Home} />

我明白了

错误:(63, 39) TS2322: 类型 '{ 精确: true;路径:字符串;成分:任何; }' 不可分配给类型 'IntrinsicAttributes & Route & { component: ComponentType; }'。

类型'IntrinsicAttributes & Route & { component: ComponentType 上不存在属性'exact'; }'。

错误:(66, 39) TS2322: Type '{ path: string;成分:任何; }' 不可分配给类型 'IntrinsicAttributes & Route & { component: ComponentType; }'。

类型'IntrinsicAttributes & Route & { component: ComponentType 上不存在属性'path'; }'。

我的代码有什么问题?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    进一步找到解决方案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,
    };
    

    【讨论】:

    • 太棒了,希望我能再投票几次。关于备忘单,我们是否真的需要在互联网偏远角落的一个角落里的网站上挖掘深奥的打字稿说明的坟墓,只是为了找到一颗钻石?或者,有没有更可靠的方法来做到这一点?
    【解决方案2】:

    我可以推荐使用

    import * as React from "react";
    import { render } from "react-dom";
    import { Route, RouteProps } from "react-router";
    
    class Home extends React.Component {
        render() {
            return <div>Home</div>;
        }
    }
    
    type LayoutRouteProps = RouteProps & {
        component: React.ComponentType;
    }
    
    const DashboardLayoutRoute = ({
        component, 
        ...rest
        }: LayoutRouteProps) => {
            const ComponentClass = component;
            const render = (props: any) => <ComponentClass {...props} />;
    
            return <Route {...rest} render={render} />;
    }
    
    const renderRoot = () => (
        <DashboardLayoutRoute exact path="/" component={Home} />
    );
    

    【讨论】:

    • 确实如此,可能最好尽可能导入类型!
    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 2020-06-30
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多