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

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.ReactNode。

其他回答

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

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

这个解决方案对我来说非常有效

interface Props {
    children: Array<ReactElement<ChildProps, JSXElementConstructor<ChildType>>>;
}

更新:一个全面的例子,这样更容易理解。

interface ChildProps {}

class ChildComponent extends React.Component<ChildProps> {}

interface ParentProps {
    children: Array<ReactElement<ChildProps, JSXElementConstructor<ChildComponent>>>;
}

class ParentComponent extends React.Component<ParentProps> {}

你应该知道任何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>
)

您也可以使用JSX。ElementChildrenAttribute

export default function Layout({children}: JSX.ElementChildrenAttribute) {
    return <div>
        {children}
    </div>
}

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

const MyComponent: React.FunctionComponent = (props) => {
    return props.children;
}