簡體   English   中英

獲取 TS 錯誤,“類型 'TPage' 上不存在屬性 'children'”

[英]Getting TS error, "Property 'children' does not exist on type 'TPage'"

我有一個這樣的組件:

type TPage = {
  title: string;
};
const Page = React.memo(({ children, title, ...rest }: TPage) => {
  return (
    <div {...rest}>
      <div>{title}</div>
      {children}
    </div>
  );
});

我用它作為,

    <Page
      title="Title"
      style={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "column"
      }}
    >
      <div>Some content</div>
    </Page>

這會引發錯誤,

const Page = React.memo(({ children, title, ...rest }: TPage) => {
                           ^^^^^^^^
Property 'children' does not exist on type 'TPage'

我嘗試通過將TType更改TType來修復它,

type TPage = React.PropsWithChildren<{
  title: string;
  children: React.ReactNode;
}>;

這解決了children的問題,但它開始抱怨style道具,說

Property 'style' does not exist on type 'IntrinsicAttributes
  & { title: string; children: ReactNode; } & { children?: ReactNode; }'

我在這里做錯了什么?

不錯的瀏覽器-y7vjd

TS 不會檢查您對道具所做的事情(使用titlechildren然后將其余部分傳遞給 div)並且不會讓您使用任何不在類型中的道具。 如果您想擴展div的功能,請將JSX類型與您的道具結合使用。

type TPage = JSX.IntrinsicElements["div"] & {
  title: string;
};

據我所知,react TypeScript 中的功能組件應該是這樣的:

type TPage = {
  title: string;
};
const Page:FC<TPage> = React.memo(({ children, title, ...rest }) => {
  return (
    <div {...rest}>
      <div>{title}</div>
      {children}
    </div>
  );
});
//FunctionalComponent can be also insted of FC

現在,在添加 FC 之后,您應該將孩子作為道具更好地編寫此內容。 現在,由於類型中缺少樣式道具,您的樣式錯誤請編寫如下類型:

 type TPage = {
      title: string;
      style: React.CSSProperties;
    };

正如你所看到的,FC 獲得通用類型來獲取 props 就像 react javascript 中的 prop-types 一樣,但是如果你將錯誤的類型傳遞給 props 而不是彈出控制台錯誤,它就不會讓你運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM