Should a component's render method have return type React.ReactNode or JSX.Element?

后端 未结 2 1404
慢半拍i
慢半拍i 2021-01-03 23:40

Both seem to result in no compilation errors, but what\'s the difference and is one preferable to the other?

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-04 00:03

    This exact question was asked over in the react-typescript-cheatsheet repo issue #57

    To quote the original answer:

    Regardless of what a component ends up rendering, React.createElement always returns an object, which is the JSX.Element interface, but React.ReactNode is the set of all possible return values of a component.

    • JSX.Element -> Return value of React.createElement
    • React.ReactNode -> Return value of a component

    Generally, I think the idea is that JSX.Element specifically describes the interface of React.createElement and is narrow in scope whereas React.ReactNode is more broad and covers all possible values that a Component could return.

提交回复
热议问题