網站搜尋

javascript - React 子元件應該設定為哪種類型的 TypeScript 型別?


這是我的佈局:

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) 設定為實際的類型而不是 any,但當我將它改為 Layout(children:ReactNode) 時,我在應用程式頁面的組件上收到這個警告:

TS2322: 類型 ‘{ children: Element; }’ 無法指派給類型 ‘IntrinsicAttributes | (IntrinsicAttributes & string) | (IntrinsicAttributes & number) | (IntrinsicAttributes & false) | (IntrinsicAttributes & true) | (IntrinsicAttributes & ReactElement<...>) | (IntrinsicAttributes & ReactNodeArray) | (IntrinsicAttributes & ReactPortal)’。 類型 ‘{ children: Element; }’ 與類型 ‘IntrinsicAttributes’ 沒有共同的屬性。

那麼我應該將它設定為 Layout(children:IntrinsicAttributes) { 這是有道理的,但當我這麼做時,沒有選項可以導入它。這應該設定為什麼?

答案#1

適用於 React 版本 >= 18 的新答案

在 React 18 中,FC 類型不再包含 children 屬性。如果你想將 children 作為 prop 添加,你將必須手動操作:

import { ReactNode } from 'react';

interface MyProps {
   children?: ReactNode;
}

const MyComponent: FC<MyProps> = (props) => {
   return props.children;
}



適用於 React 版本 < 18 的舊答案

正確為 children 打字的最佳方式是使用內建的類型 FC。

import { FC } from 'react';

如果你唯一期望的 prop 是 children:

const MyComponent: FC = (props) => {};
                       // props includes only children property

如果你想包含不只是 children 的更多屬性:

interface MyProps {
   name: string;
}

const MyComponent: FC<MyProps> = (props) => {};
                           // props includes children and name properties

答案#2

React 的型別定義有一個 PropsWithChildren 型別可以使用:

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

正如其他人所說,它被輸入為:

children?: ReactNode;