There are several ways to declare Props with children.

ReactNode

Manually add the children property directly to prop

import {ReactNode} from 'react';

type ComponentProps = {
  foo: string;
  children: ReactNode;
}
Copy the code

If children is optional, can you add an optional flag?

import {ReactNode} from 'react';

type ComponentProps = {
  foo: string; children? : ReactNode; }Copy the code

However, this approach is not recommended because children need to be added manually each time

PropsWithChildren

PropsWithChildren itself encapsulates the children declaration, source code below

// react/index.d.ts
//url:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/d076add9f29db350a19bd94c37b197729cc02f87/types/react/index .d.ts#L822
typePropsWithChildren<P> = P & { children? : ReactNode };Copy the code

So, go straight through the generic declaration

type ComponentProps = PropsWithChildren<{foo: string} >.Copy the code

The React. FunctionComponent or React. FC

When creating a functional component, the React.FC generic interface already contains the children declaration. PropsWidthChildrend is also implemented. The source code is as follows

 interfaceFunctionComponent<P = {}> { (props: PropsWithChildren<P>, context? :any): ReactElement<any.any> | null; propTypes? : WeakValidationMap<P> |undefined; contextTypes? : ValidationMap<any> | undefined; defaultProps? : Partial<P> |undefined; displayName? :string | undefined;
}
Copy the code

Depending on the interface declaration, we can pass in type parameters via generics

type ComponentProps = {
  foo: string
}

const Component: React.FC<ComponentProps> = ({foo,children}) =><span>{foo}{children}</span>
Copy the code

Class Components

When creating a class component, you need to inherit the react.componenttype

type AvatarProps = {
  src: string;
}

class Avatar extends React.Component<AvatarProps> {
  render() {
    const {src, children} = this.props;
    return <>
      <img src={src} alt="User photo" />
        {children}
    </>
  }
}
Copy the code

The last

Use functional components is recommended, so use the react. FC approach and fully embrace React Hooks

Refer to the link

www.newline.co/@bespoyasov…