组件的 render 方法是否应该具有返回类型 React.ReactNode 或 JSX.Element? [英] Should a component's render method have return type React.ReactNode or JSX.Element?
问题描述
两者似乎都不会导致编译错误,但有什么区别,一个比另一个更可取吗?
Both seem to result in no compilation errors, but what's the difference and is one preferable to the other?
推荐答案
这个确切的问题在 react-typescript-cheatsheet 回购问题 #57
无论组件最终呈现什么,React.createElement
总是返回一个对象,即 JSX.Element
接口,但 React.ReactNode
是组件所有可能返回值的集合.
Regardless of what a component ends up rendering,
React.createElement
always returns an object, which is theJSX.Element
interface, butReact.ReactNode
is the set of all possible return values of a component.
JSX.Element
->React.createElement
的返回值React.ReactNode
->组件的返回值
JSX.Element
-> Return value ofReact.createElement
React.ReactNode
-> Return value of a component
总的来说,我认为这个想法是 JSX.Element
专门描述了 React.createElement
的接口并且范围很窄,而 React.ReactNode
更广泛,涵盖了组件可以返回的所有可能值.
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.
这篇关于组件的 render 方法是否应该具有返回类型 React.ReactNode 或 JSX.Element?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!