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

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: JSX.Element[] | JSX.Element
}

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

其他回答

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

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

我用的是下面的

type Props = { children: React.ReactNode };

const MyComponent: React.FC<Props> = ({children}) => {
  return (
    <div>
      { children }
    </div>
  );

export default MyComponent;

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

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

你也可以扩展React。PropsWithChildren到你的界面,其中包含children属性。

interface Props extends React.PropsWithChildren{
    listItems: Items[],
    clickItem?: () => void,
    
}

或者您可以直接定义子元素

interface Props{
    listItems: Items[],
    clickItem?: () => void,
    children: React.ReactNode  
}

const List:FC<Props> = ({listItems,clickItem,children}) =>  {

  return (
    <>
    {children}
    </>
    
  )
}

或者你可以这样做。这是定义道具类型的另一种方式

const List = ({ children }: {children: React.ReactNode}) =>  {

你应该知道任何react组件都应该返回null或react。元素,但道具的类型。children是React。ReactNode,所以你需要使用这些道具。子元素,使babel配置元素的构造函数。 任何react组件的第二个规则是,命名的第一个字母应该是大写字母,以让react识别出该组件不是HTML标记。

代码应该是这样的。

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

另一个提示,如果你仍然使用typescript,函数组件的类型应该是React。像这样的FC

type Props = {
   title: string;
}

const Aux:React.FC<Props> = (props) =>
(
    <div>
        <h3>{props.title}</h3>
        { props.children }
        {/* children is exist by default in type React.FC */}
    </div>
)