繁体   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