添加功能组件作为属性的功能组件中“属性不存在”?

Nik*_*lai 4 typescript reactjs react-tsx react-functional-component react-typescript

我将 React 与 Typescript 和函数式方法结合使用。

const Divider: React.FunctionComponent<CardDividerProps> = (props: CardDividerProps) => (
   <div>
      divider
   </div>
);

const Card: React.FunctionComponent<CardProps> = (props: CardProps) => (
   <div>
      card
   </div>
);

Card.Divider = Divider; //Property 'Divider' does not exist on type 'FunctionComponent<CardProps>'.
Run Code Online (Sandbox Code Playgroud)

如果我从卡中删除显式类型,它就会起作用。但我想用 React.FunctionComponent 来指定它......可能吗?

我想我可以创建一个类型:

type CardWithDividerComponent = {
    (props: CardProps): JSX.Element;
    defaultProps: CardProps;
    Divider: React.FunctionComponent<CardDividerProps>;
}
Run Code Online (Sandbox Code Playgroud)

但这是唯一的解决方案吗?有什么解决办法React.FunctionComponent吗?

Dra*_*g13 5

您告诉 TypeScript 这Card是一个类型为 React.FC 的函数。该类型不包含任何属性 Divider,因此 TypeScript 对此有所抱怨。

要解决此问题,您必须告诉 TypeScript 组件的正确类型,如下所示:

const Card: React.FunctionComponent<CardProps> & {Divider?: React.FunctionComponent<CardDividerProps>} = (props: CardProps) => (
   <div>
      card
   </div>
);

Card.Divider = Divider;
Run Code Online (Sandbox Code Playgroud)