我有一个非常简单的功能组件如下:

import * as React from 'react';

export interface AuxProps  { 
    children: React.ReactNode
 }


const aux = (props: AuxProps) => props.children;

export default aux;

另一个组成部分:

import * as React from "react";

export interface LayoutProps  { 
   children: React.ReactNode
}

const layout = (props: LayoutProps) => (
    <Aux>
        <div>Toolbar, SideDrawer, Backdrop</div>
        <main>
            {props.children}
        </main>
    <Aux/>
);

export default layout;

我一直得到以下错误:

(ts) JSX元素类型“ReactNode”不是JSX元素的构造函数。 类型'undefined'不能赋值给类型'ElementClass'。[2605]

我如何正确地输入这个?


当前回答

对我来说,@ sibrens的答案还不够清楚,但我找到了这个SO答案,并将其全部内联(这可能不是最短的方法,但我发现最容易掌握的方法)。

function MyComponentWithChildren({
    customProp,
    children, /*notice the children are implicit*/
}: React.PropsWithChildren<{ customProp: any }>) {
    return <div>{children}</div>;
}

其他回答

这些答案似乎过时了- React现在有一个内置类型PropsWithChildren<{}>。它的定义类似于本页上的一些正确答案:

type PropsWithChildren<P> = P & {children?: ReactNode};

您也可以使用JSX。ElementChildrenAttribute

export default function Layout({children}: JSX.ElementChildrenAttribute) {
    return <div>
        {children}
    </div>
}

只有子节点:React.ReactNode。

这对我来说一直都很有效:

type Props = {
  children: JSX.Element;
};

这对我来说很管用:

interface Props {
  children: JSX.Element[] | JSX.Element
}

我建议使用children: React。现在改为ReactNode。