首页 文章

TypeScript和React - 子类型?

提问于
浏览
0

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

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]

如何正确输入?

2 回答

  • 1

    React组件应该有一个包装器节点或返回一个节点数组 .

    您的 <Aux>...</Aux> 组件有两个节点 divmain .

    尝试将您的孩子包装在 div Aux 组件中 .

    import * as React from 'react';
    
    export interface AuxProps  { 
      children: React.ReactNode
    }
    
    const aux = (props: AuxProps) => (<div>{props.children}</div>);
    
    export default aux;
    
  • 0

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

相关问题