interface PreProcessorProps {
error?: boolean | BooleanFunction
loading?: boolean | BooleanFunction
children: React.ReactNode | RenderFunction
}
}
const PreProcessor: React.FC = ({ children }) => {
// …
return children
}
在使用ts写React时,尴尬的遇到了这个错误

不能将类型“({ error, loading, children }: PropsWithChildren) => {} | null | undefined”分配给类型“FC”。
不能将类型“{} | null | undefined”分配给类型“ReactElement<any, any> | null”。
不能将类型“undefined”分配给类型“ReactElement<any, any> | null”。
无奈之下,只好看源代码来分析ReactNode和ReactElement的区别。

interface ReactElement<
P = any,
T extends string | JSXElementConstructor =
| string
| JSXElementConstructor

{
type: T
props: P
key: Key | null
}
ReactElement是一个接口,包含type,props,key三个属性值。该类型的变量值只能是两种: null 和 ReactElement实例

type ReactText = string | number;
type ReactChild = ReactElement | ReactText;

interface ReactNodeArray extends Array<ReactNode> {}
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

ReactNode是一种联合类型(Union Types),可以是string、number、ReactElement、{}、boolean、ReactNodeArray。由此可以看出ReactElement类型的变量可以直接赋值给ReactNode类型的变量,但是反过来是不行的。

namespace JSX {
// …
interface Element extends React.ReactElement<any, any> { }
// …
}
JSX.Element是ReactElement的子类型,并且没有增加属性,二者是兼容的。也就是说JSX.Element类型的变量可以赋值给ReactElement类型的变量,反过来赋值也成立。
综合上面所述:
JSX.Element ≈ ReactElement ⊂ ReactNode

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐