Typescript / React:带有函数语句的类型中缺少属性“children”

GN.*_*GN. 5 typescript reactjs

我有一个需要孩子的 React 组件。

收到 Typescript 错误:

Property 'children' is missing in type ... but required in type 'FixedWidthLayout'

该组件的定义类似于函数语句。

export default function FixedWidthLayout { ... }

我不想写像和表达..

IE

export const FixedWidthLayout = () => {...}

因此,做一些像...

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

..不是一个选择。

如何通过函数语句在 Typescript 中实现此功能?

sub*_*tra 6

您可以使用React.PropsWithChildren,它将为您想要传递给除 之外的组件的 props 接受一个类型参数children。组件的返回类型可以是React.ReactNode.

interface IProps {
  // props you want to pass to the component other than the children
}

export default function FixedWidthLayout(props: React.PropsWithChildren<IProps>): React.ReactNode {

  return (
    <div>
      {props.children}
      {/*The jsx code for the component*/}
    </div>
  )

}
Run Code Online (Sandbox Code Playgroud)