TypeScript and React - children type?

前端 未结 14 1175
借酒劲吻你
借酒劲吻你 2020-12-12 18:56

I have a very simple functional component as follows:

import * as React from \'react\';

export interface AuxProps  { 
    children: React.ReactNode
 }


con         


        
相关标签:
14条回答
  • 2020-12-12 19:21

    In order to use <Aux> in your JSX, it needs to be a function that returns ReactElement<any> | null. That's the definition of a function component.

    However, it's currently defined as a function that returns React.ReactNode, which is a much wider type. As React typings say:

    type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
    

    Make sure the unwanted types are neutralized by wrapping the returned value into React Fragment (<></>):

    const aux: React.FC<AuxProps> = props =>
      <>{props.children}</>;
    
    0 讨论(0)
  • 2020-12-12 19:24

    You can also use React.PropsWithChildren<P>.

    type ComponentWithChildProps = React.PropsWithChildren<{example?: string}>;
    
    0 讨论(0)
提交回复
热议问题