什么时候使用 JSX.Element、ReactNode 和 ReactElement? - When to use JSX.Element vs ReactNode vs ReactElement?

问题:

I am currently migrating a React application to TypeScript.我目前正在将 React 应用程序迁移到 TypeScript。 So far, this works pretty well, but I have a problem with the return types of my render functions respectively my function components.到目前为止,这工作得很好,但是我的render函数和函数组件的返回类型有问题。

So far, I had always used JSX.Element as return type, now this doesn't work any more if a component decides to not render anything, ie return null , since null is no valid value for JSX.Element .到目前为止,我一直使用JSX.Element作为返回类型,现在如果组件决定渲染任何内容,即返回null ,这将不再起作用,因为null不是JSX.Element This was the beginning of my journey, because now I searched the web and found that you should use ReactNode instead, which also includes null and also a few other things that can happen.这是我旅程的开始,因为现在我搜索了网络,发现您应该使用ReactNode来代替,其中还包括null以及其他一些可能发生的事情。 This seemed to be the better bet.这似乎是更好的选择。

However, now when creating a function component, TypeScript complains about the ReactNode type.但是,现在在创建函数组件时,TypeScript 会抱怨ReactNode类型。 Again, after some searching I found, that for function components you should use ReactElement instead.再次,经过一番搜索,我发现,对于函数组件,您应该使用ReactElement However, if I do so, the compatibility issue is gone, but now TypeScript again complains about null not being a valid value.但是,如果我这样做,兼容性问题就消失了,但现在 TypeScript 再次抱怨null不是有效值。

So, to cut a long story short, I have three questions:所以,长话短说,我有三个问题:

  1. What is the difference between JSX.Element , ReactNode and ReactElement ? JSX.ElementReactNodeReactElement之间有什么区别?
  2. Why do the render methods of class components return ReactNode , but function components return ReactElement ?为什么类组件的render方法返回ReactNode ,而函数组件返回ReactElement
  3. How do I solve this with respect to null ?我如何解决这个关于null

解决方案:

参考一: https://en.stackoom.com/question/3vsYA
参考二: https://stackoom.com/question/3vsYA
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章