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

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]

我如何正确地输入这个?


当前回答

你也可以扩展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}) =>  {

其他回答

为了在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}</>;

React Node是以下类型之一:

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

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

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

我用的是下面的

type Props = { children: React.ReactNode };

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

export default MyComponent;

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

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