【问题标题】:Should a component's render method have return type React.ReactNode or JSX.Element?组件的渲染方法应该有返回类型 React.ReactNode 还是 JSX.Element?
【发布时间】:2019-06-29 20:47:51
【问题描述】:

两者似乎都不会导致编译错误,但有什么区别,一个比另一个更可取?

【问题讨论】:

  • 你能举几个例子吗?

标签: reactjs typescript


【解决方案1】:

react-typescript-cheatsheet repo issue #57@ 中提出了这个确切的问题

quote the original answer

无论组件最终渲染什么,React.createElement 总是返回一个对象,即JSX.Element 接口,但React.ReactNode 是组件所有可能返回值的集合。

  • JSX.Element -> React.createElement 的返回值
  • React.ReactNode -> 组件的返回值

一般来说,我认为JSX.Element 专门描述了React.createElement 的接口并且范围很窄,而React.ReactNode 更广泛,涵盖了组件可能返回的所有可能值。

【讨论】:

  • 但是对于一个组件render()方法,它应该是render(): React.ReactNode还是render(): JSX.Element?我不确定每种方法的实际后果是什么。
  • 我认为在某些情况下,React 组件可能不会返回 JSX。您可以返回另一个函数,也可以返回 string,在这些情况下,我认为 JSX.Element 可能不起作用。
【解决方案2】:

这取决于。 ReactJS 原则上可以 render:

type RenderType = JSX.Element* | Array<RenderType> | string | number | boolean | null
// * includes Portal, Fragment
// for both function and class components
// (type doesn't exist in React type declarations)

TS 渲染类型目前为limited to:

JSX.Element 或多或少与ReactElement 相同,可以互换使用。

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2012-03-16
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多