reactjs - 对 child 使用 “React.ReactNode”类型时出错。我应该使用哪种类型?

标签 reactjs typescript compiler-errors children

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

最佳答案

React组件应返回JSX.Element。如您所见,您的 child 属于React.ReactNode类型,因此直接返回他们将无法工作。您需要将它们包装在一个元素或React.Fragment中:

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

function TestComponent(props: TestComponentProps) {
    return <React.Fragment>{props.children}</React.Fragment>;
}

关于reactjs - 对 child 使用 “React.ReactNode”类型时出错。我应该使用哪种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63898651/

相关文章:

javascript - 隐藏其他元素后将图像移动到第一个位置

css - SVG 改变动态颜色

typescript - 如何协调 monorepo 与多个 tsconfig.json,每个 tsconfig.json 都有自己的路径?

python - 不了解这些ModuleNotFound错误

c# - 我无法摆脱System.Range.get_Start错误

css对齐没有属性

javascript - 在 react 路由器中切换同一级别的路由时获取数据的正确方法?

typescript - Make 函数参数只接受来自变量对象的键

html - 在 CSS 网格布局中使用 *ngFor 在一列中不希望显示所有内容

c++ - 'L'之前缺少模板参数