【问题标题】:Container doesn't allow type children typescript容器不允许类型子打字稿
【发布时间】:2022-02-01 20:27:37
【问题描述】:

Container 是从 @material-ui/core 扩展而来的组件,它不接受 React.ReactNode 类型的子组件。

Layout.tsx:

import { Container } from "@material-ui/core";

type LayoutProps = {
  children: React.ReactNode;
};

function Layout({ children }: LayoutProps) {
  return (
    <div>
      <Container>{children}</Container>
    </div>
  );
}

它在 Container 被替换为 div 标签时起作用。所以,问题在于 MaterialUI 的 Container

我发现的唯一解决方法是编辑内部容器代码,

-    children: NonNullable<React.ReactNode>;
+    children?: React.ReactNode;

但更改内部 Container 代码以后会遇到一些问题。

还有其他方法可以解决这个问题吗?

我现在得到的类型错误是,

No overload matches this call.
  Overload 1 of 2, '(props: { component: ElementType<any>; } & { children: boolean | ReactChild | ReactFragment | ReactPortal; disableGutters?: boolean | undefined; fixed?: boolean | undefined; maxWidth?: false | ... 5 more ... | undefined; } & CommonProps<...> & Pick<...>): Element', gave the following error.
    Type 'ReactNode' is not assignable to type 'boolean | ReactChild | ReactFragment | ReactPortal'.
      Type 'undefined' is not assignable to type 'boolean | ReactChild | ReactFragment | ReactPortal'.
  Overload 2 of 2, '(props: DefaultComponentProps<ContainerTypeMap<{}, "div">>): Element', gave the following error.
    Type 'ReactNode' is not assignable to type 'boolean | ReactChild | ReactFragment | ReactPortal'.ts(2769)
Container.d.ts(6, 5): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & { component: ElementType<any>; } & { children: boolean | ReactChild | ReactFragment | ReactPortal; disableGutters?: boolean | undefined; fixed?: boolean | undefined; maxWidth?: false | ... 5 more ... | undefined; } & CommonProps<...> & Pick<...>'
Container.d.ts(6, 5): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & { children: boolean | ReactChild | ReactFragment | ReactPortal; disableGutters?: boolean | undefined; fixed?: boolean | undefined; maxWidth?: false | ... 5 more ... | undefined; } & CommonProps<...> & Pick<...>'

【问题讨论】:

    标签: reactjs typescript material-ui next.js


    【解决方案1】:

    它确实接受React.ReactNode,但该类型还包含 null 和 undefined。它是以下联合类型:

    ReactChild | ReactFragment | ReactPortal | boolean | null | undefined
    

    NonNullable&lt;React.ReactNode&gt; 只是确保不传入 null/undefined,因此它的类型为:

    ReactChild | ReactFragment | ReactPortal | boolean
    

    您只需断言children 不是空/未定义,否则只需传入一个空字符串:

    <Container>{children ?? ''}</Container>
    

    【讨论】:

    • 谢谢! &lt;Container&gt;{children!}&lt;/Container&gt; 解决了 :)
    • @SaiKrishnadas 您需要知道您的解决方案是一个逃生舱,因为它无法保证children 为空/未定义。它只会强制 TypeScript 如此看待它。使用空合并运算符更安全。
    猜你喜欢
    • 1970-01-01
    • 2016-03-21
    • 2021-06-09
    • 1970-01-01
    • 2019-07-28
    • 2021-11-15
    • 1970-01-01
    • 2022-10-25
    • 2018-12-07
    相关资源
    最近更新 更多