什麼時候使用 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章