【问题标题】:Generic props type arrow通用道具类型箭头
【发布时间】:2020-03-23 13:43:05
【问题描述】:

我对以下语法的“幕后”有点困惑 const MyComponent: FC<RouteComponentProps> = ({history}) => { }; 我见过很多这样的例子,并且明白它在传递给MyComponent 的道具对象上设置了FC<RouteComponentProp> 类型。

然而,我很困惑——我可以使用不同的语法获得 props 类型的相同逻辑结果吗? 我可以写一些像 -

const MyComponent = (FC<RouteComponentProps>:{}) => {}.

非常感谢。

【问题讨论】:

    标签: reactjs typescript generics lambda


    【解决方案1】:

    下面是FC或FunctionComponent的定义:

    interface FunctionComponent<P = {}> {
      (props: PropsWithChildren<P>, context?: any): ReactElement | null;
      propTypes?: WeakValidationMap<P>;
      contextTypes?: ValidationMap<any>;
      defaultProps?: Partial<P>;
      displayName?: string;
    }
    

    所以如果你只关心 props 和返回类型,你可以像这样复制它:

    import React, { PropsWithChildren } from 'react';
    
    // ...
    
    const MyComponent = (props: PropsWithChildren<RouteComponentProps>): ReactElement | null => {
    
    }
    

    PropsWithChildren 是一个辅助类型,它添加了标准的 react prop children,所有组件都可以使用它。 PropsWithChildren&lt;RouteComponentProps&gt;RouteComponentProps &amp; { children?: ReactNode } 相同


    但是正如您在 FunctionComponent 的定义中看到的那样,除了 props 之外,还有更多的事情要做。组件可以有许多静态属性。 propTypesdisplayName 用于开发和调试,contextTypes 用于旧的上下文 api,defaultProps 是一种为 props 做默认值的方法。

    您可能不经常使用它们,但它们是可能的,如果您确实想使用它们,则需要更新您的类型以允许它们。或者,只需使用 FC&lt;RouteComponentProps&gt; 即可立即使用。

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      相关资源
      最近更新 更多