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

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]

我如何正确地输入这个?


当前回答

您可以创建一个简单的组件,它只输出子道具,没有类型或FC(功能组件)接口。你必须用空的jsx标签<>来换行,因为子标签可以是undefined或null:

import { FC } from "react";

export const Layout: FC = (props) => {
  return <>{props.children}</>;
};

——或——

import { FC } from "react";

export const Layout: FC = ({ children }) => <>{children}</>;

其他回答

为了在JSX中使用<Aux>,它需要是一个返回ReactElement<any> | null的函数。这就是函数分量的定义。

然而,它目前被定义为一个返回React的函数。ReactNode,这是一个更广泛的类型。正如React类型所说:

type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

通过将返回值包装到React Fragment(<></>)中,确保不需要的类型被中和:

const aux: React.FC<AuxProps> = props =>
  <>{props.children}</>;

作为包含子类型的类型,我使用:

type ChildrenContainer = Pick<JSX.IntrinsicElements["div"], "children">

这个子容器类型足够通用,可以支持所有不同的情况,并且与ReactJS API保持一致。

所以,在你的例子中,它会是这样的:

const layout = ({ children }: ChildrenContainer) => (
    <Aux>
        <div>Toolbar, SideDrawer, Backdrop</div>
        <main>
            {children}
        </main>
    <Aux/>
)

React Node是以下类型之一:

布尔值(被忽略) Null或undefined(被忽略) 数量 字符串 React元素(JSX的结果) 上述任意一个的数组,可能是嵌套的数组

查找任何类型的一般方法是通过示例。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;
  ...
}

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

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

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