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

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]

我如何正确地输入这个?


当前回答

查找任何类型的一般方法是通过示例。typescript的美妙之处在于,只要你有正确的@types/ files,你就可以访问所有类型。

为了自己回答这个问题,我想到了一个react使用的组件,它有子道具。你首先想到的是什么?<div />怎么样?

你所需要做的就是打开vscode,用@types/react在react项目中创建一个新的。tsx文件。

import React from 'react';

export default () => (
  <div children={'test'} />
);

将鼠标悬停在儿童道具上显示类型。你知道什么——它的类型是ReactNode(不需要ReactNode[])。

然后,如果单击进入类型定义,它会直接将您带到来自DOMAttributes接口的子定义。

// node_modules/@types/react/index.d.ts
interface DOMAttributes<T> {
  children?: ReactNode;
  ...
}

注意:此过程应用于查找任何未知类型!他们都在那里等着你去发现他们:)

其他回答

你也可以使用React.PropsWithChildren<P>。

type ComponentWithChildProps = React.PropsWithChildren<{example?: string}>;

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

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

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

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

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

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> {}

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

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

函数组件的返回类型在TypeScript中被限制为JSXElement | null。这是当前的类型限制,纯React允许更多的返回类型。

最小的演示片段

你可以使用类型断言或片段作为解决方案:

const Aux = (props: AuxProps) => <>props.children</>; 
const Aux2 = (props: AuxProps) => props.children as ReactElement; 

ReactNode

孩子们:反应。如果目标是为Aux提供强类型,那么ReactNode可能不是最优的。

几乎任何东西都可以赋值给当前的ReactNode类型,这相当于{}| undefined | null。对于你的情况,更安全的类型可能是:

interface AuxProps {
  children: ReactElement | ReactElement[]
}

例子:

由于Aux需要React元素作为子元素,我们意外地向它添加了一个字符串。然后上面的解决方案将错误与ReactNode对比-看看链接操场。

类字子函数对于非jsx道具也很有用,比如Render Prop回调函数。