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

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]

我如何正确地输入这个?


当前回答

对我来说是JSX。元素”的作品,

interface childrenProps {
    children: JSX.Element;
}

const index = ({ children }: childrenProps) => {
    return (
        <>
            <NavBar />
            {children}
        </>
    );
};

export default index;

其他回答

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

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

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

你可以像这样声明你的组件:

const MyComponent: React.FunctionComponent = (props) => {
    return props.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[];
}

这对我来说很管用:

interface Props {
  children: JSX.Element[] | JSX.Element
}

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