组件的 render 方法是否应该具有返回类型 React.ReactNode 或 JSX.Element? [英] Should a component's render method have return type React.ReactNode or JSX.Element?

查看:37
本文介绍了组件的 render 方法是否应该具有返回类型 React.ReactNode 或 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 the JSX.Element interface, but React.ReactNode is the set of all possible return values of a component.

  • JSX.Element ->React.createElement
  • 的返回值
  • React.ReactNode ->组件的返回值
  • JSX.Element -> Return value of React.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆