【问题标题】:Property 'children' does not exist on type '{}'类型“{}”上不存在属性“子项”
【发布时间】:2022-06-22 09:15:45
【问题描述】:

我遇到打字稿错误。它表示类型“{}”上不存在“孩子”,即使此语法适用于我的其他项目。

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

我猜这个新应用在 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}</>
}

【讨论】:

    【解决方案2】:

    您还没有为React.FC定义类型

    修复可能是

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

    【讨论】:

      【解决方案3】:

      您需要通过以下方式替换解构的道具参数

      { children }: {children: React.ReactNode}
      

      【讨论】:

        【解决方案4】:

        正如其他人所说,React 18 从 props 类型定义中删除了 children

        您可以改为执行以下操作,明确声明您的 props 应包含子项:

        import { FunctionComponent, PropsWithChildren } from 'react';
        
        export const MyComponent: FunctionComponent<PropsWithChildren<{}>> =
          ({ children }) => <div>{children}</div>;
        

        【讨论】:

          猜你喜欢
          • 2020-03-25
          • 2020-11-24
          • 2021-08-04
          • 1970-01-01
          • 2021-01-09
          • 2019-05-13
          • 1970-01-01
          • 2021-07-10
          相关资源
          最近更新 更多