簡體   English   中英

類型“{}”上不存在屬性“children”

[英]Property 'children' does not exist on type '{}'

我有一個 typescript 錯誤。 它說 'children' 在類型 '{}' 上不存在,即使這種語法適用於我的其他項目。

我猜這個新應用程序是基於 React 18 的。

React 18 從FC類型中移除了children 如果你想要它回來,你需要自己將它添加到道具中。

const Foo: React.FC<{ children: React.ReactNode }> = ({ children }) => <>{children}</>

或者最好根本不使用FC類型:

interface Props {
    children: React.ReactNode
}

function Foo({ children }: Props) {
    return<>{children}</>
}

您還沒有為React.FC定義類型

修復可能是

type Props = {
   children: React.ReactNode
}

const Page: React.FC<Props> = ({ children }) => {
  ...
}

正如其他人所提到的,React 18 從 props 類型定義中刪除了children

您可以通過明確聲明您的道具應包括孩子來執行以下操作:

import { FunctionComponent, PropsWithChildren } from 'react';

export const MyComponent: FunctionComponent<PropsWithChildren> =
  ({ children }) => <div>{children}</div>;

以上將道具默認為unknown類型。

您還可以定義道具:

import { FunctionComponent, PropsWithChildren } from 'react';

interface Props {
  label: string;
}

export const MyComponent: FunctionComponent<PropsWithChildren<Props>> =
  ({ label, children }) => <div>{label}: {children}</div>;

或者更好:

import { FunctionComponent, PropsWithChildren } from 'react';

interface Props extends PropsWithChildren {
  label: string;
}

export const MyComponent: FunctionComponent<Props> =
  ({ label, children }) => <div>{label}: {children}</div>;

您需要通過以下方式替換 destructured props 參數

{ children }: {children: React.ReactNode}

暫無
暫無

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

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