[React Typescript] React.ReactNode > React.ReactElement = JSX.Element = React.JSX.Element

发布时间 2023-08-22 15:44:41作者: Zhentiw

This is ReactNode:

type ReactNode =
        | ReactElement
        | string
        | number
        | ReactFragment
        | ReactPortal
        | boolean
        | null
        | undefined

 

This is React.ReactElement:

    interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
        type: T;
        props: P;
        key: Key | null;
    }

 

This is JSX.Element:

interface Element extends React.ReactElement<any, any> { }

 

Basicly: JSX.Element === React.ReactElement

Those are working fine:

const Component = (): JSX.Element => {
  return <div></div>;
};

const Component2 = (): React.ReactNode => {
  return <div></div>;
};

<>
  <Component2 />
</>;

const Component3 = (): React.ReactElement => {
  return <div></div>;
};

<>
  <Component3 />
</>;

 

But if you return number, string, null or undefined, then you can only use React.ReactNode

const Component4 = (): React.ReactElement => {
  return "hello!"; // Error
};

const Component4 = (): React.ReactNode => {
  return "hello!"; // Works
};