简体   繁体   中英

TypeScript React SFC children props type error

I have the following stateless functional component defined:

import { SFC } from "react";

type ProfileTabContentProps = {
  selected: boolean;
};

const ProfileTabContent: SFC<ProfileTabContentProps> = ({ selected, children }) => selected && children;

This fails to compile with the following error:

Type '({ selected, children }: ProfileTabContentProps & { children?: ReactNode; }) => ReactNode' is not assignable to type 'StatelessComponent'.
Type 'ReactNode' is not assignable to type 'ReactElement | null'.
Type 'undefined' is not assignable to type 'ReactElement | null'.

A quick search for related questions all give the same answer, which is very similar to what I've done. What am I missing?

Your problem is that selected && children evaluates to React.ReactNode , which if you check the typings, is a union type:

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

However, a React.SFC must return a ReactElement , it's definition for the function definition is:

(props: P & { children?: ReactNode }, context?: any): ReactElement<any> | null;

I think you've seen the [truthy] && [render me] pattern used a lot, but usually inside of a larger TSX component, where a React.ReactNode is allowed

You could do this if you want to keep it simple:

const ProfileTabContent: SFC<ProfileTabContentProps> = ({ selected, children }) => 
  <>{selected && children}</>

Which just wraps up your expression inside the shorthand for a React.ReactFragment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM