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

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<P>。

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

其他回答

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

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

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

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

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

您可以创建一个简单的组件,它只输出子道具,没有类型或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}</>;

你可以使用ReactChildren和ReactChild:

import React, { ReactChildren, ReactChild } from 'react';
 
interface AuxProps {
  children: ReactChild | ReactChildren;
}

const Aux = ({ children }: AuxProps) => (<div>{children}</div>);

export default Aux;

如果你需要传递平面数组的元素:

interface AuxProps {
  children: ReactChild | ReactChild[] | ReactChildren | ReactChildren[];
}