問題:
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:所以,長話短說,我有三個問題:
- What is the difference between
JSX.Element
,ReactNode
andReactElement
?JSX.Element
、ReactNode
和ReactElement
之間有什麼區別? - Why do the
render
methods of class components returnReactNode
, but function components returnReactElement
?爲什麼類組件的render
方法返回ReactNode
,而函數組件返回ReactElement
? - How do I solve this with respect to
null
?我如何解決這個關於null
?
解決方案:
參考一: https://en.stackoom.com/question/3vsYA參考二: https://stackoom.com/question/3vsYA