React children 应该设置为什么 TypeScript 类型?

Cit*_*zen 4 javascript typescript reactjs next.js

这是我的布局:

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

而我的应用程序:

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}
Run Code Online (Sandbox Code Playgroud)

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

TS2322: 类型 '{children: Element; }' 不可分配给类型 'IntrinsicAttributes | (IntrinsicAttributes & string) | (IntrinsicAttributes & number) | (IntrinsicAttributes & false) | (IntrinsicAttributes & true) | (IntrinsicAttributes & ReactElement<...>) | (IntrinsicAttributes & ReactNodeArray) | (IntrinsicAttributes & ReactPortal)'。类型'{孩子:元素; }' 与类型 'IntrinsicAttributes' 没有共同的属性。

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

kin*_*ser 11

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

interface LayoutProps {
   children: React.ReactNode;
}

function Layout({ children }: LayoutProps) {
Run Code Online (Sandbox Code Playgroud)

  • 对于“const Layout: FC = (props) =&gt; {}”,使用“{props.children}”会返回一个错误,指出“类型 {}”上不存在“children”。 (2认同)

ger*_*rod 6

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

function Layout({ children }: React.PropsWithChildren<{}>) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

children?: ReactNode;
Run Code Online (Sandbox Code Playgroud)