对子代使用类型“ React.ReactNode”时出现错误我应该使用哪种类型?

问题描述

使用函数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>;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...