类型“{}”上不存在属性“children”

Jer*_*avo 11 typescript reactjs

我遇到打字稿错误。它说类型“{}”上不存在“children”,尽管此语法适用于我的其他项目。

Ale*_*yne 29

我猜这个新应用程序是在 React 18 上运行的。

childrenReact 18从类型中删除FC。如果你想要它回来,你需要自己将其添加到道具中。

const Foo: React.FC<{ children: React.ReactNode }> = ({ children }) => <>{children}</>
Run Code Online (Sandbox Code Playgroud)

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

interface Props {
    children: React.ReactNode
}

function Foo({ children }: Props) {
    return<>{children}</>
}
Run Code Online (Sandbox Code Playgroud)


Nic*_* Vu 8

您还没有定义类型React.FC

修复方法可能是

type Props = {
   children: React.ReactNode
}

const Page: React.FC<Props> = ({ children }) => {
  ...
}
Run Code Online (Sandbox Code Playgroud)


Bar*_*jen 7

正如其他人提到的,React 18children从 props 类型定义中删除了。

您可以通过明确声明您的 props 应包含子项来执行以下操作:

import { FunctionComponent, PropsWithChildren } from 'react';

export const MyComponent: FunctionComponent<PropsWithChildren> =
  ({ children }) => <div>{children}</div>;
Run Code Online (Sandbox Code Playgroud)

上面将默认 props 的类型unknown

您还可以定义道具:

import { FunctionComponent, PropsWithChildren } from 'react';

interface Props {
  label: string;
}

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

或者甚至更好:

import { FunctionComponent, PropsWithChildren } from 'react';

interface Props extends PropsWithChildren {
  label: string;
}

export const MyComponent: FunctionComponent<Props> =
  ({ label, children }) => <div>{label}: {children}</div>;
Run Code Online (Sandbox Code Playgroud)