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

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]

我如何正确地输入这个?


当前回答

这个解决方案对我来说非常有效

interface Props {
    children: Array<ReactElement<ChildProps, JSXElementConstructor<ChildType>>>;
}

更新:一个全面的例子,这样更容易理解。

interface ChildProps {}

class ChildComponent extends React.Component<ChildProps> {}

interface ParentProps {
    children: Array<ReactElement<ChildProps, JSXElementConstructor<ChildComponent>>>;
}

class ParentComponent extends React.Component<ParentProps> {}

其他回答

来自TypeScript网站:https://github.com/Microsoft/TypeScript/issues/6471

推荐的做法是将props类型写成{children?: 任何}

这对我很管用。子节点可以是很多不同的东西,因此显式类型可能会遗漏一些情况。

关于后续问题有一个更长的讨论:https://github.com/Microsoft/TypeScript/issues/13618,但任何方法仍然有效。

只有子节点:React.ReactNode。

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

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

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

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

你可以像这样声明你的组件:

const MyComponent: React.FunctionComponent = (props) => {
    return props.children;
}