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

lo7*_*lo7 4 children compiler-errors typescript reactjs

使用LoaderIndicator()渲染子项的function 时收到错误消息,loading = false请参阅下面的代码。React.ReactNode当我使用而不是 type时出现错误any,但通常我使用React.ReactNodeas type 为孩子。这是我得到的错误:

'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;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 13

React 组件应该返回JSX.Element. 正如你所看到的,你的孩子属于 类型React.ReactNode,所以直接归还他们是行不通的。您需要将它们包装在元素或 React.Fragment 内:

type TestComponentProps = {
    children?: React.ReactNode;
}

function TestComponent(props: TestComponentProps) {
    return <React.Fragment>{props.children}</React.Fragment>;
}
Run Code Online (Sandbox Code Playgroud)

  • 这使得 linter 说“片段应该包含多个子片段 - 否则,根本不需要片段”。:( (2认同)