问题描述
使用函数LoaderIndicator()
时会得到错误消息,该函数会呈现子级,而在loading = false
时,请参见下面的代码。当我使用React.ReactNode
而不是类型any
时出现错误,但是通常我将React.ReactNode
用作儿童类型。这是我得到的错误:
'LoaderIndicator' cannot be used as a JSX component. Its return type '{}' is not a valid JSX element. Type '{}' is missing the following properties from type 'Element': type,props,key. ts(2786)
我不知道如何解决此错误,我已经尝试了几乎所有方法,有人可以提供帮助吗? :)
export type LoaderIndicatorProps = {
loading: boolean;
children?: React.ReactNode;
};
export function LoaderIndicator(props: LoaderIndicatorProps) {
const { loading,children } = props;
if (loading) {
return (
<div>
<Container>
<Icon />
<h3 style={{ color: "#ffffff" }}>Wait for a moment...</h3>
</Container>
</div>
);
} else {
return children;
}
}
解决方法
反应组件应返回JSX.Element
。如您所见,您的孩子属于React.ReactNode
类型,因此直接返回他们将不起作用。您需要将它们包装在一个元素或React.Fragment中:
type TestComponentProps = {
children?: React.ReactNode;
}
function TestComponent(props: TestComponentProps) {
return <React.Fragment>{props.children}</React.Fragment>;
}