我有以下代码(codesandbox):
import { ComponentType, ReactNode } from "react";
type DatetimeCell = ({ value }: { value: string }) => ReactNode;
function getDateTimeCell(): DatetimeCell {
return ({ value }) => value;
}
function buildCell({
value
}: {
value: string;
}): ComponentType<{ value: string }> {
const DateTimeCell = getDateTimeCell();
return ({ value }) => <DateTimeCell value={value} />;
}
Run Code Online (Sandbox Code Playgroud)
返回时buildCell
出现错误:
'DateTimeCell' cannot be used as a JSX component.
Its return type 'ReactNode' is not a valid JSX element. …
Run Code Online (Sandbox Code Playgroud) 我目前正在将React应用程序迁移到TypeScript。到目前为止,这很好,但是我render
分别对函数的返回类型和函数组件有问题。
到目前为止,我一直将其JSX.Element
用作return类型,现在,如果组件决定不呈现任何内容(即return)null
,null
则此方法将不再起作用,因为没有有效的value JSX.Element
。这是我旅程的开始,因为现在我在网上搜索并发现您应该使用ReactNode
它,它还包括null
可能发生的其他一些事情。这似乎是更好的选择。
但是,现在在创建功能组件时,TypeScript会抱怨ReactNode
类型。再次,经过一些搜索,我发现对于功能组件,应该ReactElement
改为使用。但是,如果我这样做了,兼容性问题就消失了,但是现在TypeScript再次抱怨null
不是有效值。
因此,总而言之,我有三个问题:
JSX.Element
,ReactNode
和ReactElement
?render
类组件的方法返回ReactNode
,而函数组件返回ReactElement
?null
呢?