When to use JSX.Element vs ReactNode vs ReactElement?

前端 未结 2 787
面向向阳花
面向向阳花 2020-12-04 05:44

I am currently migrating a React application to TypeScript. So far, this works pretty well, but I have a problem with the return types of my render functions re

2条回答
  •  心在旅途
    2020-12-04 06:25

    What is the difference between JSX.Element, ReactNode and ReactElement?

    A ReactElement is an object with a type and props.

     interface ReactElement

    = string | JSXElementConstructor> { type: T; props: P; key: Key | null; }

    A ReactNode is a ReactElement, a ReactFragment, a string, a number or an array of ReactNodes, or null, or undefined, or a boolean:

    type ReactText = string | number;
    type ReactChild = ReactElement | ReactText;
    
    interface ReactNodeArray extends Array {}
    type ReactFragment = {} | ReactNodeArray;
    
    type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
    

    JSX.Element is a ReactElement, with the generic type for props and type being any. It exists, as various libraries can implement JSX in their own way, therefore JSX is a global namespace that then gets set by the library, React sets it like this:

    declare global {
      namespace JSX {
        interface Element extends React.ReactElement { }
      }
    }
    

    By example:

     

    // <- ReactElement = JSX.Element // <- ReactElement = JSX.Element {true && "test"} // <- ReactNode

    Why do the render methods of class components return ReactNode, but function components return ReactElement?

    Indeed, they do return different things. Components return:

     render(): ReactNode;
    

    And functions are "stateless components":

     interface StatelessComponent

    { (props: P & { children?: ReactNode }, context?: any): ReactElement | null; // ... doesn't matter }

    This is actually due to historical reasons.

    How do I solve this with respect to null?

    Type it as ReactElement | null just as react does. Or let Typescript infer the type.

    source for the types

提交回复
热议问题