【问题标题】:What TypeScript type should React children be set to?React children 应该设置为什么 TypeScript 类型?
【发布时间】:2021-02-19 16:09:59
【问题描述】:

这是我的布局:

export default function Layout(children:any) {
  return (
    <div className={`${styles.FixedBody} bg-gray-200`}>
      <main className={styles.FixedMain}>
        <LoginButton />
        { children }
      </main>

      <footer>
        <FooterNavigation />
      </footer>
    </div>
  )
}

还有我的应用:

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

为了使我的代码更简洁,我想将Layout(children:any) 设置为实际类型而不是任何类型,但是当我将其更改为Layout(children:ReactNode) 时,我在组件上的应用页面上收到此警告:

TS2322:类型 '{ 孩子:元素; }' 不可分配给类型 '内在属性 | (IntrinsicAttributes & 字符串) | (IntrinsicAttributes & number) | (IntrinsicAttributes & false) | (IntrinsicAttributes & true) | (内在属性 & 反应元素<...>) | (IntrinsicAttributes & ReactNodeArray) | (IntrinsicAttributes & ReactPortal)'。类型'{孩子:元素; }' 与类型“IntrinsicAttributes”没有共同的属性。

我应该将它设置为Layout(children:IntrinsicAttributes) { 是有道理的,但是当我这样做时,没有选项可以导入它。这应该设置成什么?

【问题讨论】:

  • 应该设置为ReactNode

标签: javascript reactjs typescript next.js


【解决方案1】:

React 的类型有一个PropsWithChildren type,你可以使用:

function Layout({ children }: React.PropsWithChildren<{}>) {
    // ...
}

正如其他人所说,它的类型为:

children?: ReactNode;

【讨论】:

    【解决方案2】:

    props 是一个对象 - childrenprops 对象内的一个嵌套字段。

    interface LayoutProps {
       children: React.ReactNode;
    }
    
    function Layout({ children }: LayoutProps) {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-24
      • 2019-06-30
      • 2021-10-27
      • 2018-12-24
      • 2021-02-19
      • 1970-01-01
      • 2019-11-21
      • 2018-12-05
      相关资源
      最近更新 更多