问题:
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